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") }
This library is based on an annotation processor that helps to organize, discover, search, and visualize Jetpack Compose UI elements. It provides a UI with minimal settings that allow you to quickly find your components, colors, and typography.
Instead of passing as String instead pass as Hexadecimal. For example if you want this #9CCC65
Color just remove the front #
and replace it with 0xFF. Example
val PrimaryBlue = Color(0xFF9CCC65)
You can use this object class with a getColor method.
object HexToJetpackColor { fun getColor(colorString: String): Color { return 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With