2012-05-05 102 views
5

我的应用程序中有一些滑块允许用户更改ARGB颜色,但是我需要将这些值转换为十六进制值,如0xff000000,它是纯黑的。将RGBA值转换为十六进制颜色代码

这是我到目前为止有:

protected int toHex(Color col) { 
    String as = pad(Integer.toHexString(col.getAlpha())); 
    String rs = pad(Integer.toHexString(col.getRed())); 
    String gs = pad(Integer.toHexString(col.getGreen())); 
    String bs = pad(Integer.toHexString(col.getBlue())); 
    String hex = "0x" + as + rs + gs + bs; 
    return Integer.parseInt(hex, 16); 
} 

private static final String pad(String s) { 
    return (s.length() == 1) ? "0" + s : s; 
} 

然而在获得整数值如下图所示,我得到了输入字符串NumberFormatException异常:“0xccffffff”:

int color = toHex(new Color(153f, 153f, 153f, 0.80f)); 

任何想法上如何获得这个整数?谢谢。

回答

4

颜色参数必须在1f和0f之间浮动。所以这是一个有效的颜色:

int color = toHex(new Color(1f, 1f, 1f, 1f)); 

这是白色的。

+0

啊,谢谢。现在排序了。我为我的字体使用Slick,现在我已将Color切换为java.awt.Color。 – Kaikz

0

问题是你包含alpha值。 所以你的最大颜色代码是#FFFFFFFF(8位数字)。

方法Integer.parseInt将让您解析从-0x800000000x7FFFFFFF的值。为了从中得到你的价值0xCC999999,你将不得不否定价值和输入-0x33666667 - 这当然是没有用的。

笨重而稳定的解决方法是使用Long

(int) Long.parseLong(text, 16) 
相关问题