I want to convert Android color to Compose color. But I don't know how.
I used these code but these codes have Error and my App crashes.
val currColor = task.startDate.time.toColor()
var test = lerp(Color.Red,Color.Blue,265f)
And
var test = Color(ArgbEvaluator().evaluate(20f,Color.Red,Color.Blue) as Int)
I checked that link too. How to convert android.graphics.Color to androidx.compose.ui.graphics.Color
So how can I convert android.graphics.color to androidx.compose.ui.graphics.color ?
You can convert it with
val int = android.graphics.Color.RED
val color = Color(int)
but you neither need conversion nor ArgbEvaluator().evaluate() to changer color based on fraction.
Compose has lerp function that takes two Compose Colors and fraction to change color based on fraction which is between 0f and 1f
lerp(Color.Red,Color.Blue,265f)
should be between 0f and 1f
/**
 * Linear interpolate between two [Colors][Color], [start] and [stop] with [fraction] fraction
 * between the two. The [ColorSpace] of the result is always the [ColorSpace][Color.colorSpace]
 * of [stop]. [fraction] should be between 0 and 1, inclusive. Interpolation is done
 * in the [ColorSpaces.Oklab] color space.
 */
@Stable
fun lerp(start: Color, stop: Color, /*@FloatRange(from = 0.0, to = 1.0)*/ fraction: Float): Color {
    val colorSpace = ColorSpaces.Oklab
    val startColor = start.convert(colorSpace)
    val endColor = stop.convert(colorSpace)
    val startAlpha = startColor.alpha
    val startL = startColor.red
    val startA = startColor.green
    val startB = startColor.blue
    val endAlpha = endColor.alpha
    val endL = endColor.red
    val endA = endColor.green
    val endB = endColor.blue
    val interpolated = Color(
        alpha = lerp(startAlpha, endAlpha, fraction),
        red = lerp(startL, endL, fraction),
        green = lerp(startA, endA, fraction),
        blue = lerp(startB, endB, fraction),
        colorSpace = colorSpace
    )
    return interpolated.convert(stop.colorSpace)
}
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