How to get Color object in java from css-style string which describes color?

有些话、适合烂在心里 提交于 2020-01-25 13:11:27

问题


For example, I have strings #0f0, #00FF00, green and in all cases I want to transform them to Color.GREEN.

Are there any standard ways or maybe some libraries have necessary functionality?


回答1:


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.



来源:https://stackoverflow.com/questions/2826894/how-to-get-color-object-in-java-from-css-style-string-which-describes-color

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