如何从描述颜色的css样式字符串中获取java中的Color对象?

发布于 2024-09-01 01:24:37 字数 147 浏览 6 评论 0原文

例如,我有字符串 #0f0#00FF00green,在所有情况下我都想将它们转换为 Color.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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画离情绘悲伤 2024-09-08 01:24:38

首先,如果以下内容没有帮助,我深表歉意 - 也就是说,如果您已经知道如何执行此操作并且只是在寻找一个库来为您执行此操作。我不知道有哪个图书馆可以做到这一点,尽管它们肯定存在。

在您作为示例给出的 3 个字符串中,#00FF00 是最容易转换的。

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

如果您有像 green 这样的颜色词,那么您需要首先检查所有 CSS 识别的颜色是否都在 Java 常量内。如果是这样,您可以使用反射来从中获取常量值(首先将它们大写)。

如果没有,您可能需要自己创建 CSS 字符串到颜色的映射。无论如何,这可能是最干净的方法。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文