Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color from hex string in jetpack compose

Tags:

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") } 
like image 958
Vipul Asri Avatar asked Feb 16 '20 10:02

Vipul Asri


People also ask

Is jetpack compose a library?

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.


2 Answers

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) 
like image 132
Mayank Wadhwa Avatar answered Sep 21 '22 15:09

Mayank Wadhwa


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.

like image 22
Tigran Ghazinyan Avatar answered Sep 19 '22 15:09

Tigran Ghazinyan