Reputation: 8242
How to convert from Compose Color to Android Color Int?
I am using this code for the moment and it seems to be working, I can't seem to find a function to get the Int value of the color
Color.rgb(color.red.toInt(), color.green.toInt(), color.blue.toInt())
where Color.rgb
is a function android.graphics.Color
that returns an Integer color and color variable is just a Compose Color !
Since the float one requires higher API
Linked : How to convert android.graphics.Color to androidx.compose.ui.graphics.Color
Upvotes: 48
Views: 20112
Reputation: 363737
You can use the toArgb()
method
Converts this color to an ARGB color int. A color int is always in the sRGB color space
Something like:
//Compose Color androidx.compose.ui.graphics
val Teal200 = Color(0xFFBB86FC)
//android.graphics.Color
val color = Teal200.toArgb()
You can also use something like:
//android.graphics.Color
val color = android.graphics.Color.argb(
Teal200.toArgb().alpha,
Teal200.toArgb().red,
Teal200.toArgb().green,
Teal200.toArgb().blue
)
Upvotes: 72
Reputation: 858
Worked for me convert to Argb, then convert to string:
fun Int.hexToString() = String.format("#%06X", 0xFFFFFF and this)
fun getStringColor(color: Color): String {
return color.toArgb().hexToString()
}
fun someOperation() {
val color = Color.White //compose color
val colorAsString = getStringColor(color)
print(colorAsString)
}
// Result will be: "#FFFFFF"
Upvotes: 3
Reputation: 4289
The Android Compose Color
class now has function toArgb(), which converts to Color Int.
The function documentation says:
Converts this color to an ARGB color int. A color int is always in the sRGB color space. This implies a color space conversion is applied if needed.
-> No need for a custom conversion function anymore.
Upvotes: 9
Reputation: 3903
Here's a spin on the answer from @gabriele with some Kotlin sugar:
//Compose Color androidx.compose.ui.graphics
val Teal200 = Color(0xFFBB86FC)
fun Color.toAGColor() = toArgb().run { android.graphics.Color.argb(alpha, red, green, blue) }
//android.graphics.Color
val color = Teal200.toAGColor()
Upvotes: 0