[英]Using Java, can I convert a human readable color name into an integer array?
Using Java, how do I convert a human readable color name into a three-element integer array? 使用Java,如何将人类可读的颜色名称转换为三元素整数数组?
For example, I have a color represented by: 例如,我有一种颜色,表示为:
int[] RGB_COLOR = {128,25,25};
And I want to be able to convert the static value Color.BLUE
into a three-element integer array that is similar to the one above. 而且我希望能够将静态值
Color.BLUE
转换为与上面的相似的三元素整数数组。 Is this possible or do I have to hack my way around this? 这可能吗,还是我必须解决这个问题?
Do you mean like this... 你是说这个意思吗
Color c = Color.BLUE;
int[] RGB = { c.getRed(), c.getGreen(), c.getBlue() };
To convert a colour name to a Color you can use reflections, provided its own of the built in colours. 要将颜色名称转换为颜色,可以使用反射,前提是它具有内置的颜色。 If you want more colours you would need to use a map.
如果需要更多颜色,则需要使用地图。
public static Color colorOf(String color) {
try {
return (Color) Color.class.getDeclaredField(color).get(null);
} catch(Exception notAvailable) {
return null; // ??
}
}
只需使用Color
类的getGreen()
, getRed()
, getBlue()
方法
scroll down on the doc you linked 向下滚动您链接的文档
Color c = //...;
int[] color = {c.getRed(),c.getGreen(),c.getBlue()};
The simplest way to get a Color
object from a String
would be to create a Map<String, Color>
mapping the valid String
color names to Color
objects. 从
String
获取Color
对象的最简单方法是创建Map<String, Color>
将有效的String
颜色名称映射到Color
对象。
Map<String, Color> map = new HashMap<String, Color>();
map.put("BLUE", Color.BLUE);
// etc.
Color color = map.get(someString);
Also, I'd recomment not storing the RGB values in an int[3]
unless you really need that because some 3rd party code expects it or something. 另外,我建议不要将RGB值存储在
int[3]
除非您确实需要这样做,因为某些第三方代码会期望它或类似的东西。 Just using the Color
class is much more appropriate in general. 通常,仅使用
Color
类更为合适。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.