如何从描述颜色的css样式字符串中获取java中的Color对象?
例如,我有字符串 #0f0
、#00FF00
、green
,在所有情况下我都想将它们转换为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,如果以下内容没有帮助,我深表歉意 - 也就是说,如果您已经知道如何执行此操作并且只是在寻找一个库来为您执行此操作。我不知道有哪个图书馆可以做到这一点,尽管它们肯定存在。
在您作为示例给出的 3 个字符串中,
#00FF00
是最容易转换的。如果您有
#0f0
...如果您有像
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.If you have
#0f0
...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.