将RGBA值转换为十六进制颜色代码

Kai*_*ikz 5 java hex colors argb

我的应用程序中有一些滑块允许用户更改ARGB颜色,但我需要将这些值转换为十六进制值,如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;
}
Run Code Online (Sandbox Code Playgroud)

但是在获得如下的Integer值后,我得到输入字符串的NumberFormatException:"0xccffffff":

int color = toHex(new Color(153f, 153f, 153f, 0.80f));
Run Code Online (Sandbox Code Playgroud)

有关如何将其转换为整数的任何想法?谢谢.

Wez*_*zum 4

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

int color = toHex(new Color(1f, 1f, 1f, 1f));
Run Code Online (Sandbox Code Playgroud)

这是白色的。