我想将HEX颜色(如#FF0000)转换为十进制颜色(如16711680)。我该怎么做呢?
我已经尝试过使用Color类,但我找不到正确转换颜色的方法。
Color hexcolor = Color.decode("#FF0000");
//And then?
分析解答
验证input的一种方法可能是:
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);
}
但由于需要知道内部表示,因此不建议这样做。