Javaの - 小数の色にHEXの色を変換します

Stijn Bannink:

私は(16711680など)小数色にHEX色(のように#FF0000)を変換したいです。どのように私はこれを行うために必要なのですか?

私はすでにColorクラスを使用してみましたが、私は正確に色を変換するための方法を見つけることができません。

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

一つの方法の検証の入力は次のようになります。

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

しかし、内部表現を知っている必要があるため、これは推奨されません。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=227947&siteId=1
おすすめ