Java中的颜色类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23346208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:06:31  来源:igfitidea点击:

Color Class in Java

javaawt

提问by

I have a question regarding the awt Colorclass in Java.

我有一个关于ColorJava 中的 awt类的问题。

I am currently using the class abbreviations such as Color.REDand Color.BLACK. I also have a list of three integers such as the following:

我目前正在使用类缩写,例如Color.REDColor.BLACK。我还有一个包含三个整数的列表,如下所示:

int var1 = 0
int var2 = 0
int var3 = 255

Is there a method to convert these integers into the appropriate Java Colorname?

有没有一种方法可以将这些整数转换为适当的 JavaColor名称?

采纳答案by The Guy with The Hat

There is no way to do this with a single method in the Java core classes. However, you can fairly easily do this yourself in two ways.

无法使用 Java 核心类中的单个方法来做到这一点。但是,您可以通过两种方式自己轻松完成此操作。

First way

第一种方式

Create a new Colorout of the RGB values you have:

Color从您拥有的 RGB 值中创建一个新的:

Color color = new Color(var1, var2, var3);

Then

然后

  1. Get the Classobject from the Colorclass with getClass().
  2. Get the elements from that with getEnumConstants().
  3. Stream it using Arrays.stream()
  4. Filter it by calling filter(), so it only contains all the enum constants that equal the color you made (there should be either one or zero).
  5. Use toArray()to turn the stream into an array.
  6. Get the first element of that array with [0]. This will throw an ArrayIndexOutOfBoundsExceptionif there isn't a predefined color matching your color.
  7. Get the name of that color with Enum's toString().
  1. ClassColor类中获取对象getClass()
  2. 从中获取元素getEnumConstants()
  3. 使用流式传输 Arrays.stream()
  4. 通过调用过滤它filter(),所以它只包含所有等于你制作的颜色的枚举常量(应该有一个或零)。
  5. 使用toArray()打开流成一个数组。
  6. 使用 获取该数组的第一个元素[0]ArrayIndexOutOfBoundsException如果没有与您的颜色匹配的预定义颜色,这将抛出一个。
  7. 使用Enum's获取该颜色的名称toString()
String colorName = Arrays.stream(Color.getClass().getEnumConstants())
                         .filter(c -> c.equals(color))
                         .toArray()[0]
                         .toString();

Second way

第二种方式

First, create a HashMapof Colors that contains all the colors you want:

首先,创建一个包含你想要的所有颜色HashMapColors :

HashMap<Color, String> colors = new HashMap<Color, String>();

colors.put(Color.BLACK,            "BLACK");
colors.put(Color.BLUE,             "BLUE");
colors.put(Color.CYAN,             "CYAN");
colors.put(Color.DARK_GRAY,        "DARK_GRAY");
colors.put(Color.GRAY,             "GRAY");
colors.put(Color.GREEN,            "GREEN");
colors.put(Color.LIGHT_GRAY,       "LIGHT_GRAY");
colors.put(Color.MAGENTA,          "MAGENTA");
colors.put(Color.ORANGE,           "ORANGE");
colors.put(Color.PINK,             "PINK");
colors.put(Color.RED,              "RED");
colors.put(Color.WHITE,            "WHITE");
colors.put(new Color(192, 0, 255), "PURPLE");
colors.put(new Color(0xBADA55),    "BADASS_GREEN");
colors.put(new Color(0, 0, 128),   "DARK_BLUE");

Then, create a new Colorout of the RGB values you have:

然后,Color从您拥有的 RGB 值中创建一个新的:

Color color = new Color(var1, var2, var3);

Last, getthe value in colorsfor the key color:

最后,键get的值:colorscolor

String colorName = colors.get(color);

回答by nils

Without any helping libraries I would say: No. Especially because not every RGB-Color has a specific name. However, you could of course build an own function, which tries to match some of the available colors and deliver something like "Unknown" if there is no match.

如果没有任何帮助库,我会说:不。特别是因为并非每个 RGB 颜色都有特定的名称。但是,您当然可以构建一个自己的函数,它会尝试匹配一些可用的颜色,并在不匹配时提供诸如“未知”之类的东西。

The matching attempt could theoretically be done using the Java reflection API...

理论上可以使用 Java 反射 API 来完成匹配尝试...

回答by Sireesh Yarlagadda

As far as i know, we don't have any such library to directly access the colors from the Constants.

据我所知,我们没有任何这样的库来直接访问来自 Constants 的颜色

But we can manage do it using Hex Color Library in Java.

但是我们可以使用 Java 中的十六进制颜色库来管理它。

References :

参考 :

  1. Hex

  2. Color Class

  1. 十六进制

  2. 颜色等级

回答by Farmer Joe

There is no set function for this kind of behavior, but you could do something like this:

这种行为没有设置函数,但您可以执行以下操作:

public static String getColorName(int r, int g, int b) {
    String[] colorNames = new String[] {
            "BLACK",
            "BLUE",
            "GREEN",
            "CYAN",
            "DARK_GRAY",
            "GRAY",
            "LIGHT_GRAY",
            "MAGENTA",
            "ORANGE",
            "PINK",
            "RED",
            "WHITE",
            "YELLOW"
    };
    Color userProvidedColor = new Color(r,g,b);
    Color color;
    Field field;
    for (String colorName : colorNames) {
        try {
            field = Class.forName("java.awt.Color").getField(colorName);
            color = (Color)field.get(null);
            if (color.equals(userProvidedColor)) {
                return colorName; // Or maybe return colorName.toLowerCase() for aesthetics
            }
        } catch (Exception e) {

        }
    }
    Color someOtherCustomDefinedColorMaybePurple = new Color(128,0,128);
    if (someOtherCustomDefinedColorMaybePurple.equals(userProvidedColor)) {
        return "Purple";
    }
    return "Undefined";
}

There are a few options from here as well, maybe you want the nearest color? In which case you could try and resolve the distance somehow (here by distance from each r,g,b coordinate, admittedly not the best method but simple enough for this example, this wiki page has a good discussion on more rigorous methods)

这里也有一些选择,也许你想要最接近的颜色?在这种情况下,您可以尝试以某种方式解决距离(此处通过与每个 r、g、b 坐标的距离,诚然不是最好的方法,但对于此示例来说足够简单,此 wiki 页面对更严格的方法进行了很好的讨论

// ...
String minColorName = "";
float minColorDistance = 10000000;
float thisColorDistance = -1;
for (String colorName : colorNames) {
    try {
        field = Class.forName("java.awt.Color").getField(colorName);
        color = (Color)field.get(null);
        thisColorDistance = ( Math.abs(color.red - userProvidedColor.red) + Math.abs(color.green - userProvidedColor.green) + Math.abs(color.blue - userProvidedColor.blue) );
        if (thisColorDistance < minColorDistance) {
            minColorName = colorName;
            minColorDistance = thisColorDistance;
        }
    } catch (Exception e) {
        // exception that should only be raised in the case color name is not defined, which shouldnt happen
    }
}
if (minColorName.length > 0) {
    return minColorName;
}
// Tests on other custom defined colors

This should outline how you would be able to compare to the built in colors from the Colorlibrary. You could use a Mapto expand the functionality further to allow for you to define as many custom colors as you like (Something @TheGuywithTheHatsuggests as well) which gives you more control over the return names of matched colors, and allows for you to go by more colors than just the predefined ones:

这应该概述您将如何与Color库中的内置颜色进行比较。您可以使用 aMap进一步扩展功能,以允许您根据需要定义任意数量的自定义颜色(@TheGuywithTheHat 也建议),这使您可以更好地控制匹配颜色的返回名称,并允许您通过比预定义的颜色更多的颜色:

HashMap<String,Color> colorMap = new HashMap<String,Color>();

colorMap.put("Red",Color.RED);
colorMap.put("Purple",new Color(128,0,128));
colorMap.put("Some crazy name for a color", new Color(50,199,173));
// etc ...

String colorName;
Color color;
for (Map.Entry<String, Color> entry : colorMap.entrySet()) {
    colorName = entry.getKey();
    color= entry.getValue();
    // Testing against users color
}