Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert android.graphics.Color to androidx.compose.ui.graphics.Color

I'm drawing a JetpackCompose Canvas

    Canvas(modifier = modifier.clipToBounds()) {
        val colorEvaluator = ArgbEvaluator()
        colorEvaluator.evaluate(t, Color.Red, Color.Blue)
        drawCircle(
            style = Stroke(8.dp.toPx()),
            color = AndroidColor.valueOf(colorEvaluator.evaluate(t, Color.Red, Color.Blue) as Int),
            center = Offset(size.minDimension/2 , size.minDimension/2),
            radius = size.minDimension * t)
        drawRect(
            color = darkColor,
            style = Stroke(16.dp.toPx()),
        )
    }

Where

import androidx.compose.ui.graphics.Color
import android.graphics.Color as AndroidColor

I got this error on color = AndroidColor.valueOf(colorEvaluator.evaluate(t, Color.Red, Color.Blue) as Int), where the error message is

Type mismatch.
Required:
androidx.compose.ui.graphics.Color
Found:
android.graphics.Color
like image 391
Elye Avatar asked Oct 11 '20 11:10

Elye


1 Answers

Looks like I should supply AndroidColor.RED and AndroidColor.BLUE to the ArgbEvaluator instead of accidentally use the Color of Compose

Where AndroidColor is import android.graphics.Color as AndroidColor

    Canvas(modifier = modifier.clipToBounds()) {
        drawCircle(
            style = Stroke(8.dp.toPx()),
            color = Color(ArgbEvaluator().evaluate(t, AndroidColor.RED, AndroidColor.BLUE) as Int),
            center = Offset(size.minDimension / 2, size.minDimension / 2),
            radius = size.minDimension * t
        )
        drawRect(
            color = darkColor,
            style = Stroke(16.dp.toPx()),
        )
    }

Updated

Found an even better approach, that is to use lerp in compose as per the below code. Using this approach, we no longer need to use the old ArgbEvaluator.

    Canvas(modifier = modifier.clipToBounds()) {
        drawCircle(
            style = Stroke(8.dp.toPx()),
            color = lerp(Color.Red, Color.Blue, t),
            center = Offset(size.minDimension / 2, size.minDimension / 2),
            radius = size.minDimension * t
        )
        drawRect(
            color = darkColor,
            style = Stroke(16.dp.toPx()),
        )
    }
like image 70
Elye Avatar answered Oct 19 '22 11:10

Elye