How to get Color object in java from css-style string which describes color?
For example, I have strings #0f0
, #00FF00
, green
and in all cases 开发者_JS百科I want to transform them to Color.GREEN
.
Are there any standard ways or maybe some libraries have necessary functionality?
First, I apologize if the below isn't helpful - that is, if you know how to do this already and were just looking for a library to do it for you. I don't know of any libraries that do this, though they certainly may exist.
Of the 3 strings you gave as an example, #00FF00
is the easiest to transform.
String colorAsString = "#00FF00";
int colorAsInt = Integer.parseInt(colorAsString.substring(1), 16);
Color color = new Color(colorAsInt);
If you have #0f0
...
String colorAsString = "#0f0";
int colorAsInt = Integer.parseInt(colorAsString.substring(1), 16);
int R = colorAsInt >> 8;
int G = colorAsInt >> 4 & 0xF;
int B = colorAsInt & 0xF;
// my attempt to normalize the colors - repeat the hex digit to get 8 bits
Color color = new Color(R << 4 | R, G << 4 | G, B << 4 | B);
If you have the color word like green
, then you'll want to check first that all CSS-recognized colors are within the Java constants. If so, you can maybe use reflection to get the constant values from them (uppercase them first).
If not, you may need to create a map of CSS strings to colors yourself. This is probably the cleanest method anyway.
精彩评论