Get value of R, G, B by color

2019-08-02 23:50发布

问题:

I have user type the color (e.g. White, Red,...) so how can I get value of R, G, B with the color of user gave?

I have a function (float r, float g, float b) to set color a node. So i let the user type the color name they want, then i want to convert that color name to get r, g, b value for my function.

回答1:

Color defines a limited number of enums representing basic colours. This code excerpt uses reflection to map from their names to the RGB representations.

Other than that you'll have to maintain a map of colors/RGB values, or possibly a set of system properties, and use Color.getColor(String name).



回答2:

Create a Map which contains all your optional colors as Strings together with their RGB representation (For the record, Color is found in the java.awt package):

Map<String,Color> colorMap = new HashMap<String,Color>();
        colorMap.put("white", new Color(255,255,255));
        colorMap.put("red", new Color(255,0,0));

Then use the text entered by the user to lookup your Color in the map:

String userColor = <whereever you get your string from>;
Color result = colorMap.get(userColor.toLowerCase());

Finally, use this Color object which has int values for RGB to retrieve the float values you need and pass them to your function:

yourFunction(Float.valueOf(result.getRed(),Float.valueOf(result.getGreen()),Float.valueOf(result.getBlue()));

If possible I would advise to use integers instead of floats for your RGB, as it will range from 0 to 255 in whole numbers in most if not all cases.

A good place to get all the colors you'd ever need with their RGB's is this website: http://cloford.com/resources/colours/500col.htm



回答3:

If you have the color as a String you lookup this Color in a map and this will give you the Red, Green and Blue values.



标签: java colors rgb