我想使用一个类似于 "#FFFF0000"
的十六进制字符串中的颜色来改变布局的背景颜色。
Color.HSVToColor
看起来是一个不错的选择,但它需要一个 float[]
参数。
我离解决方案还有多远?
((TextView) view).setBackgroundResource(R.drawable.your_color_here);
/**
* Input: Hex Value of ARGB, eg: "#FFFF00FF", "#FF00FF", "#F0F"
* Output: Float Color Array with with red, green,
* blue and alpha (opacity) values,
* eg: floatArrayOf(0.63671875f, 0.76953125f, 0.22265625f, 1.0f)
*/
private fun getFloatArrayFromARGB(argb: String): FloatArray {
val colorBase: Int = if (argb.length == 4) {
val red = if (argb[1] == '0') 0 else 255
val green = if (argb[2] == '0') 0 else 255
val blue = if (argb[3] == '0') 0 else 255
Color.rgb(red, green, blue)
} else {
Color.parseColor(argb)
}
val red = Color.red(colorBase)
val green = Color.green(colorBase)
val blue = Color.blue(colorBase)
val alpha = Color.alpha(colorBase)
return floatArrayOf(
red / 255f,
green / 255f,
blue / 255f,
alpha / 255f
)
}
用法:
private val colorValue = getFloatArrayFromARGB("#F0F")
希望它能帮助到某些人
没有预定义的类可以直接从十六进制代码实现到颜色名称,所以你需要尝试键值对概念,简单地遵循这段代码。
String hexCode = "Any Hex code" //#0000FF
HashMap<String, String> color_namme = new HashMap<String, String>();
color_namme.put("#000000", "Black");
color_namme.put("#000080", "Navy Blue");
color_namme.put("#0000C8", "Dark Blue");
color_namme.put("0000FF", "Blue");
color_namme.put("000741", "Stratos");
color_namme.put("001B1C", "Swamp");
color_namme.put("002387", "Resolution Blue");
color_namme.put("002900", "Deep Fir");
color_namme.put("002E20", "Burnham");
for (Map.Entry<String, String> entry : color_namme.entrySet()) {
String key = (String) entry.getKey();
String thing = (String) entry.getValue();
if (hexCode.equals(key))
Color_namme.setText(thing); //Here i display using textview
}
对于缩短的十六进制代码
int red = colorString.charAt(1) == '0' ? 0 : 255;
int blue = colorString.charAt(2) == '0' ? 0 : 255;
int green = colorString.charAt(3) == '0' ? 0 : 255;
Color.rgb(red, green,blue);
fun String.toColor(): Int? {
return if (this.isNotEmpty()) {
Color.parseColor(this)
} else {
null
}