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

Integer的值为-16776961

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

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

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


当前回答

在Koltin中使用这种方法

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

其他回答

在Koltin中使用这种方法

var hexColor = "#${Integer.toHexString(ContextCompat.getColor(context, R.color.colorTest))}"
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);

如果使用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 hexColor = String.format("#%06X", (0xFFFFFF & intColor));

或者这个是

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