Hello, I'm trying to animate the background of a b...
# compose
n
Hello, I'm trying to animate the background of a button using multiple brushes. (code in thread 🧵) I have 2 concerns: • I'm creating (allocating) a new brush every frame. It seems wasteful. • I just need to alternate between 3 brushes but it seems too verbose. How can I improve this code?
Copy code
val infiniteTransition = rememberInfiniteTransition(label = "background")

val colors = remember {
    listOf(
        Color(0xFF3B0A8C),
        Color(0xFF5009DC),
        Color(0xFF6B21A8),
        Color(0xFF7C3AED),
    )
}
val edgeColor by infiniteTransition.animateColor(
    initialValue = colors[0],
    targetValue = colors[0],
    animationSpec = infiniteRepeatable(
        animation = keyframes {
            durationMillis = 3_000

            colors[0] at 0 using EaseInOut
            colors[1] at 750 using EaseInOut
            colors[2] at 1_500 using EaseInOut
            colors[1] at 2_250 using EaseInOut
            colors[0] at 3_000 using EaseInOut
        },
    ),
)
val centerColor by infiniteTransition.animateColor(
    initialValue = colors[1],
    targetValue = colors[1],
    animationSpec = infiniteRepeatable(
        animation = keyframes {
            durationMillis = 3_000

            colors[1] at 0 using EaseInOut
            colors[2] at 750 using EaseInOut
            colors[3] at 1_500 using EaseInOut
            colors[2] at 2_250 using EaseInOut
            colors[1] at 3_000 using EaseInOut
        },
    ),
)

Button(
    modifier = modifier.background(
        brush = Brush.horizontalGradient(
            listOf(
                edgeColor,
                centerColor,
                edgeColor,
            )
        ),
    ),
    onClick = {},
    colors = ButtonDefaults.buttonColors().copy(
        containerColor = Color.Transparent,
    ),
) {}