本文介绍了如何获得Color对象从描述颜色的CSS样式的字符串java吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个字符串#0f0 #00FF00 绿色和我想将它们转换成 Col​​or.GREEN 所有案件。

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?

推荐答案

首先,我道歉,如果下面的是没有帮助的 - 也就是说,如果你知道如何已经做到这一点并只是在寻找一个库做为你。我不知道这样做的任何库,但他们肯定会存在的。

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.

你给作为一个例子3串,#00FF00 是最容易改变。

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);

如果您有#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);

如果你有一个像绿色的颜色的话,那么你会希望先检查所有的CSS认可的颜色是Java的常量中。如果是这样,你也许可以使用反射来得到他们的常数值(大写他们在前)。

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).

如果没有,你可能需要创建地图CSS串到自己的颜色。这可能是最干净的方法呢。

If not, you may need to create a map of CSS strings to colors yourself. This is probably the cleanest method anyway.

这篇关于如何获得Color对象从描述颜色的CSS样式的字符串java吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 17:26