What is compose equivalent of OvershootInterpolator?

Viewed 454

On Android views, we had an animation using an OvershootInterpolator

We want to replicate the same animation in Jetpack Compose. I see that there are several AnimationSpec described in https://developer.android.com/jetpack/compose/animation but I don't see which one might replicate the OvershootInterpolator

  • tween spec doesn't seem to do any overshoot, just animating between start and end value without overshooting

  • spring spec does overshooting, however it doesn't have a durationMillis parameter as tween, so we can't control how fast it plays

  • keyFrames spec seems a possible solution by doing something like this:

              animationSpec = keyframes {
                  durationMillis = 500
                  0f at 100 with FastOutSlowInEasing
                  // Overshoot value to 50f
                  50f * 2 at 300 with LinearOutSlowInEasing
                  // Actual final value after overshoot animation
                  25f at 500
              }
    

Is there a better / simpler way than using keyFrames to replicate OvershootInterpolator?

2 Answers

We can use spring animation of compose to achieve OvershootInterpolator. Even though we cannot provide any custom duration for the animation, we can control the speed of the animation using the stiffness attribute.

We can put any custom float values to the stiffness attribute. androidx.compose.animation.core currently provides 4 stiffness constant values by default i.e,

object Spring {
    /**
     * Stiffness constant for extremely stiff spring
     */
    const val StiffnessHigh = 10_000f

    /**
     * Stiffness constant for medium stiff spring. This is the default stiffness for spring
     * force.
     */
    const val StiffnessMedium = 1500f

    /**
     * Stiffness constant for a spring with low stiffness.
     */
    const val StiffnessLow = 200f

    /**
     * Stiffness constant for a spring with very low stiffness.
     */
    const val StiffnessVeryLow = 50f
    .....
}

We can check which stiffness suits our case.

For eg:- (medium speed)

animationSpec = spring(
    dampingRatio = Spring.DampingRatioHighBouncy,
    stiffness = Spring.StiffnessMedium // with medium speed
)

We can also put a custom value to the stiffness for eg:-

 animationSpec = spring(
    dampingRatio = Spring.DampingRatioHighBouncy, // this would define how far the overshoot would happen.
    stiffness = 1000f // with custom speed less than medium speed.
)

You can play around with custom float values for stiffness to achieve your ideal duration for the animation.

Related