我想将十六进制颜色(如#FF0000)转换为十进制颜色(如 16711680)。我需要怎么做?
我已经尝试过使用 Color 类,但找不到正确转换颜色的方法。
Color hexcolor = Color.decode("#FF0000");
//And then?
最佳答案
验证输入的一种方法是:
public static int parseHex(final String color) {
final Matcher mx = Pattern.compile("^#([0-9a-z]{6})$", CASE_INSENSITIVE).matcher(color);
if(!mx.find())
throw new IllegalArgumentException("invalid color value");
return Integer.parseInt(mx.group(1), 16);
}
虽然不是必需的,但您可以分别解析每个颜色分量:
public static int parseColor(final String color) {
final Matcher mx = Pattern.compile("^#([0-9a-z]{2})([0-9a-z]{2})([0-9a-z]{2})$", CASE_INSENSITIVE).matcher(color);
if(!mx.find())
throw new IllegalArgumentException("invalid color value");
final int R = Integer.parseInt(mx.group(1), 16);
final int G = Integer.parseInt(mx.group(2), 16);
final int B = Integer.parseInt(mx.group(3), 16);
return (R << 16) + (G << 8) + B;
}
如果 Color
不是问题,您可以使用:
public static int parseColor(final String color) {
final Color c = Color.decode(color);
return (c.getRed() << 16) + (c.getGreen() << 8) + c.getBlue();
}
另一方面,你也可以这样做:
public static int parseColor(final String color) {
return 0xFFFFFF & (Color.decode(color).getRGB() >> 8);
}
但由于需要知道内部表示,所以不推荐这样做。
关于Java - 将十六进制颜色转换为十进制颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56609709/