【问题标题】:Java - Convert a HEX color to a decimal colorJava - 将十六进制颜色转换为十进制颜色
【发布时间】:2019-10-29 18:32:04
【问题描述】:

我想将十六进制颜色(如 #FF0000)转换为十进制颜色(如 16711680)。我需要怎么做?

我已经尝试过使用 Color 类,但找不到正确转换颜色的方法。

Color hexcolor = Color.decode("#FF0000");
//And then?

【问题讨论】:

  • FF0000 十六进制是 16711680 十进制,所以你对待“颜色”就像对待任何其他数字一样。
  • 哦,谢谢!我想我可以找到一些东西。没想到这么简单。

标签: java colors hex decimal


【解决方案1】:

由于vlumi的评论,我已经找到了anwser。

https://www.javatpoint.com/java-hex-to-decimal

public static int convertHEXtoDecimal(String HEX) {
    String hex = HEX.replaceAll("#", "");
    String digits = "0123456789ABCDEF";
    hex = hex.toUpperCase();
    int val = 0;
    for (int i = 0; i < hex.length(); i++) {
        char c = hex.charAt(i);
        int d = digits.indexOf(c);
        val = 16 * val + d;
    }
    return val;
}

【讨论】:

  • 使用Integer.parseInt 看起来更好。
【解决方案2】:

验证输入的一种方法可能是:

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);
}

但由于需要知道内部表示,所以不建议这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 2017-10-30
    • 2012-07-25
    • 2015-05-19
    • 2020-08-05
    相关资源
    最近更新 更多