Issue
How to parse hex string e.g. #9CCC65
in Color class in jetpack compose.
P.S: option seem to be missing in jetpack compose package
Current Workaround:
Exported parseColor()
method from standard Color class.
@ColorInt
fun parseColor(@Size(min = 1) colorString: String): Int {
if (colorString[0] == '#') { // Use a long to avoid rollovers on #ffXXXXXX
var color = colorString.substring(1).toLong(16)
if (colorString.length == 7) { // Set the alpha value
color = color or -0x1000000
} else require(colorString.length == 9) { "Unknown color" }
return color.toInt()
}
throw IllegalArgumentException("Unknown color")
}
Solution
You can use this object class with a getColor method.
object HexToJetpackColor {
fun getColor(colorString: String): Color {
return Color(android.graphics.Color.parseColor("#" + colorString))
}
}
Or we can use an extension function
fun Color.fromHex(color: String) = Color(android.graphics.Color.parseColor("#" + colorString))
Jetpack Color class i.e androidx.ui.graphics.Color
only takes RGB, ARGB, ColorSpace and colorInt in constructor. See: Color.kt
so, here we are directly accessing parseColor()
method from android.graphics.Color
which returns colorInt.
Hence parseColor() method can be used to get colorInt and then providing it to Jetpack Color class to get androidx.ui.graphics.Color
object.
Answered By - burkinafaso3741
Answer Checked By - Clifford M. (JavaFixing Volunteer)