在Java中给定Color对象获取相应的十六进制颜色代码的方法?

时间:2013-02-27 13:58:37

标签: java class colors hex decode

我已经检查了Color的Java类文档,发现我可以使用(e.g. "#FFFFFF")方法从十六进制代码字符串Color.decode();生成一个Color对象。

我想为我正在处理的项目实现反向过程,但似乎没有为此类内置的方法。

有一种简单的方法吗?

4 个答案:

答案 0 :(得分:19)

String.format("#%06x", color.getRGB() & 0x00FFFFFF)

掩码用于删除alpha分量,位24-31

答案 1 :(得分:3)

Color color = Color.BLUE;
Formatter f = new Formatter(new StringBuffer("#"));
f.format("%02X", color.getRed());
f.format("%02X", color.getGreen());
f.format("%02X", color.getBlue());
f.toString(); //#0000FF

答案 2 :(得分:1)

阅读本文:Getting Html color codes with a JColorChooser

答案有一种将颜色转换为十六进制值的方法。

答案 3 :(得分:0)

还有另一种方式。以为我只是添加了这个替代方案。

// ARGB = (255, 255, 0, 0) (Red) 
// hex -> "ffff0000"
String hex = Integer.toHexString(color.getRGB());

// Reduced to RGB: hex -> "#ff0000"
hex = "#" + hex.substring(2, hex.length());