我有一个从android。graphics。color生成的整数

Integer的值为-16776961

如何将此值转换为格式为#RRGGBB的十六进制字符串

简单地说:我想从-16776961输出#0000FF

注意:我不希望输出包含alpha,我也尝试了这个例子没有任何成功


当前回答

尝试Integer.toHexString ()

来源: 在Java中,如何将字节数组转换为十六进制数字字符串,同时保持前导零?

其他回答

我相信我已经找到了答案,这段代码将整数转换为十六进制字符串并删除alpha。

Integer intColor = -16895234;
String hexColor = "#" + Integer.toHexString(intColor).substring(2);

请注意,只有在确定删除alpha不会影响任何事情的情况下才使用此代码。

蒙版确保你只得到RRGGBB, %06X给你零填充十六进制(总是6个字符长):

String hexColor = String.format("#%06X", (0xFFFFFF & intColor));

使用这个方法Integer。toHexString,当使用color . parseccolor时,你可以对某些颜色有一个Unknown color异常。

使用这个方法String。format("#%06X", (0xFFFFFF & intColor)),你将失去alpha值。

所以我推荐这个方法:

public static String ColorToHex(int color) {
        int alpha = android.graphics.Color.alpha(color);
        int blue = android.graphics.Color.blue(color);
        int green = android.graphics.Color.green(color);
        int red = android.graphics.Color.red(color);

        String alphaHex = To00Hex(alpha);
        String blueHex = To00Hex(blue);
        String greenHex = To00Hex(green);
        String redHex = To00Hex(red);

        // hexBinary value: aabbggrr
        StringBuilder str = new StringBuilder("#");
        str.append(alphaHex);
        str.append(blueHex);
        str.append(greenHex);
        str.append(redHex );

        return str.toString();
    }

    private static String To00Hex(int value) {
        String hex = "00".concat(Integer.toHexString(value));
        return hex.substring(hex.length()-2, hex.length());
    }
String int2string = Integer.toHexString(INTEGERColor); //to ARGB
String HtmlColor = "#"+ int2string.substring(int2string.length() - 6, int2string.length()); // a stupid way to append your color

ARGB颜色的整数值为十六进制字符串:

String hex = Integer.toHexString(color); // example for green color FF00FF00

十六进制字符串到整数值的ARGB颜色:

int color = (Integer.parseInt( hex.substring( 0,2 ), 16) << 24) + Integer.parseInt( hex.substring( 2 ), 16);