我有一个从android。graphics。color生成的整数
Integer的值为-16776961
如何将此值转换为格式为#RRGGBB的十六进制字符串
简单地说:我想从-16776961输出#0000FF
注意:我不希望输出包含alpha,我也尝试了这个例子没有任何成功
我有一个从android。graphics。color生成的整数
Integer的值为-16776961
如何将此值转换为格式为#RRGGBB的十六进制字符串
简单地说:我想从-16776961输出#0000FF
注意:我不希望输出包含alpha,我也尝试了这个例子没有任何成功
当前回答
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);
其他回答
修复了颜色选择器库中的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;
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);
蒙版确保你只得到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
你可以使用这个没有alpha的颜色:
String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
或者这个是
String hexColor = String.format("#%08X", (0xFFFFFFFF & intColor));