将RGBA值转换为hex颜色代码
我的应用程序中有一些滑块允许用户更改ARGB颜色,但我需要将这些值转换为hex值,如0xff000000,它是纯黑色。
这是我到目前为止:
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; }
但是在获得如下的Integer值后,我得到输入字符串的NumberFormatException:“0xccffffff”:
int color = toHex(new Color(153f, 153f, 153f, 0.80f));
关于如何将其转换为整数的任何想法? 谢谢。
Color参数必须在1f和0f之间浮动。 所以这是一个有效的颜色:
int color = toHex(new Color(1f, 1f, 1f, 1f));
哪个是白色的。
问题是你包含了alpha值。 所以你的最大颜色代码是#FFFFFFFF
(8位数)。
方法Integer.parseInt
将允许您将值从-0x80000000
解析为0x7FFFFFFF
。 为了从它获得你的值0xCC999999
,你必须否定该值并输入-0x33666667
– 这当然没有用。
笨重但稳定的解决方法是使用Long
。
(int) Long.parseLong(text, 16)