0

RGB値をHex形式で保存できるように、Javaでコーダー/デコーダーを作成しようとしています。私はこのようなコーダーを持っています:

System.out.println("#" + Integer.toHexString(label.getColor().getRed())
    + Integer.toHexString(label.getColor().getGreen())
    + Integer.toHexString(label.getColor().getBlue()));

そしてデコーダは次のようになります:

System.out.println(decodeColor("#"
    + Integer.toHexString(label.getColor().getRed())
    + Integer.toHexString(label.getColor().getGreen())
    + Integer.toHexString(label.getColor().getBlue())));

decodeColor()関数の実装は次のとおりです。

private RGB decodeColor(String attribute) {
    Integer intval = Integer.decode(attribute);
    int i = intval.intValue();
    return new RGB((i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);
}

テスト プログラムを実行すると、次の出力が得られます。

  • 初期値は new RGB(15, 255, 45)

<\label ... color="#fff2d">...</label>

RGB {15、255、45}

  • 初期値はRGB(15,0,45)

<\label ... color="#f02d">...</label>

RGB {0、240、45}

したがって、場合によっては正しい結果が返されますが、他の場合は完全にめちゃくちゃになります。何故ですか?

4

2 に答える 2

3

#rrggbb は常に色成分ごとに 2 桁の 16 進数を必要とするためです。

String s = String.format("#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue());

Color c = Color.decode(s);
于 2013-09-20T10:31:32.143 に答える
0
Integer intval = Integer.decode(attribute);

ここでは、文字列attributeは で始まりますが、#で始まる必要があり0xます。

private RGB decodeColor(String attribute) {
    String hexValue = attribute.replace("#", "0x");

    int i = Integer.decode(hexValue).intValue();
    return new RGB((i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);
}
于 2013-09-20T10:34:08.830 に答える