animationandroid-jetpack-composepager

animateColorAsState depending of a progress from 0 to 1


I have a Pager from which I get the position progress from 0 to 1. I would like to change the background color of the Surface that contains the Pager depending on the PagerState the same way I was able to do it for alphas:

val alphaAnimation by animateFloatAsState(
    targetValue = progress, // <- derivedStateOf PagerState
    animationSpec = spring(stiffness = Spring.StiffnessMedium),
    label = ""
)

Is it possible to use the same progress between 2 color values?

I didn't find a way using for animateColorAsState


Solution

  • If you wish to use a float value between 0f and 1f for changing between 2 colors you can use linear interpolation function for Color which is

    fun lerp(start: Color, stop: Color, @FloatRange(from = 0.0, to = 1.0) fraction: Float): Color
    

    For instance as lerp(Color.Red, Color.Green, progress) can be used to change color based on pager swipe if you change the range from 0f to 1f.