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

Integer的值为-16776961

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

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

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


当前回答

这是我所做的

 int color=//your color
 Integer.toHexString(color).toUpperCase();//upercase with alpha
 Integer.toHexString(color).toUpperCase().substring(2);// uppercase without alpha

谢谢你们的回答

其他回答

如果使用Integer。当你像0xFF000123一样转换颜色时,你将以错过的零结束。 这是我的基于kotlin的解决方案,它既不需要android特定的类也不需要java。所以你也可以在多平台项目中使用它:

    fun Int.toRgbString(): String =
        "#${red.toStringComponent()}${green.toStringComponent()}${blue.toStringComponent()}".toUpperCase()

    fun Int.toArgbString(): String =
        "#${alpha.toStringComponent()}${red.toStringComponent()}${green.toStringComponent()}${blue.toStringComponent()}".toUpperCase()

    private fun Int.toStringComponent(): String =
        this.toString(16).let { if (it.length == 1) "0${it}" else it }

    inline val Int.alpha: Int
        get() = (this shr 24) and 0xFF

    inline val Int.red: Int
        get() = (this shr 16) and 0xFF

    inline val Int.green: Int
        get() = (this shr 8) and 0xFF

    inline val Int.blue: Int
        get() = this and 0xFF

修复了颜色选择器库中的alpha问题。

如果在选择颜色时返回一个整数值,则首先将其转换为十六进制颜色。

    String hexVal = String.format("#%06X", (0xFFFFFFFF & 
    color)).toUpperCase();

    int length=hexVal.length();
    String withoutHash=hexVal.substring(1,length);


    while (withoutHash.length()<=7)
    {

        withoutHash="0"+withoutHash;

    }
    hexVal ="#"+withoutHash;

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

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

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

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

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

这是我所做的

 int color=//your color
 Integer.toHexString(color).toUpperCase();//upercase with alpha
 Integer.toHexString(color).toUpperCase().substring(2);// uppercase without alpha

谢谢你们的回答