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

Integer的值为-16776961

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

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

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


当前回答

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

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

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

其他回答

在Koltin中使用这种方法

var hexColor = "#${Integer.toHexString(ContextCompat.getColor(context, R.color.colorTest))}"

尝试Integer.toHexString ()

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

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

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

如果使用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

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