Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert androidx.compose.ui.graphics.Color to android.graphics.Color (int)

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

like image 872
Waqas Tahir Avatar asked Apr 16 '21 07:04

Waqas Tahir


People also ask

What is color INT for Android?

Denotes that the annotated element represents a packed color int, AARRGGBB . If applied to an int array, every element in the array represents a color integer.

What color formats are supported for color resources in Android?

red(int) to extract the red component. green(int) to extract the green component. blue(int) to extract the blue component.

What RGB does Android use?

A range of valid RGB values (most commonly [0..1] ). The most commonly used RGB color space is sRGB .

What is Androidx compose?

Build better apps faster with. Jetpack Compose. Jetpack Compose is Android's modern toolkit for building native UI. It simplifies and accelerates UI development on Android. Quickly bring your app to life with less code, powerful tools, and intuitive Kotlin APIs.


2 Answers

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 = android.graphics.Color.argb(
    Teal200.toArgb().alpha,
    Teal200.toArgb().red,
    Teal200.toArgb().green,
    Teal200.toArgb().blue
    )

You can also use:

val color = Teal200.toAGColor() 
like image 119
Gabriele Mariotti Avatar answered Oct 13 '22 14:10

Gabriele Mariotti


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.

like image 45
Peter F Avatar answered Oct 13 '22 15:10

Peter F