Converting RGB values into color

不打扰是莪最后的温柔 提交于 2019-12-11 06:59:34

问题


I have a java code that returns decimal values as shown below

 [1.0, 0.0, 0.0] for Red  
 [0.0, 1.0, 0.0] for Green 

the first value denotes the color code for Red, the second value denotes color code for Green and the third value denotes Color code for Blue.

Is there any way we can convert these RGB values into the respective color in java?


回答1:


There are an example to return the color name which depend on using Reflection to get the name of the color (java.awt.Color)

public static String getNameReflection(Color colorParam) {
        try {
            //first read all fields in array
            Field[] field = Class.forName("java.awt.Color").getDeclaredFields();
            for (Field f : field) {
                String colorName = f.getName();
                Class<?> t = f.getType();
                if (t == java.awt.Color.class) {
                    Color defined = (Color) f.get(null);
                    if (defined.equals(colorParam)) {
                        System.out.println(colorName);
                        return colorName.toUpperCase();
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("Error... " + e.toString());
        }
        return "NO_MATCH";
    }

and in the main

        Color colr = new Color(1.0f, 0.0f, 0.0f);
        Main m = new Main();
        m.getNameReflection(colr);
    }

You have to know that :"java.awt.Color" defined this colors:

white
WHITE
lightGray
LIGHT_GRAY
gray
GRAY
darkGray
DARK_GRAY
black
BLACK
red
RED
pink
PINK
orange
ORANGE
yellow
YELLOW
green
GREEN
magenta
MAGENTA
cyan
CYAN
blue
BLUE


来源:https://stackoverflow.com/questions/20193997/converting-rgb-values-into-color

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!