【问题标题】:What is compose equivalent of OvershootInterpolator?OvershootInterpolator 的组成等价物是什么?
【发布时间】:2021-05-10 14:02:26
【问题描述】:

在 Android 视图中,我们有一个使用 OvershootInterpolator 的动画

我们希望在 Jetpack Compose 中复制相同的动画。 我看到https://developer.android.com/jetpack/compose/animation 中描述了几个 AnimationSpec,但我看不出哪一个可以复制 OvershootInterpolator

  • tween 规范似乎没有做任何超调,只是在开始和结束值之间设置动画而没有超调

  • spring 规范会过冲,但是它没有 durationMillis 参数作为补间,所以我们无法控制它的播放速度

  • keyFrames 规范似乎是一个可能的解决方案,方法是这样做:

              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
              }
    

有没有比使用keyFrames 复制OvershootInterpolator 更好/更简单的方法?

【问题讨论】:

    标签: android android-animation android-jetpack-compose


    【解决方案1】:

    您可以通过自定义Easing 使用来自Animator 世界的任何Interpolator

    animationSpec = tween(easing = Easing {
        OvershootInterpolator().getInterpolation(it) 
    })
    

    Easing接口:https://developer.android.com/reference/kotlin/androidx/compose/animation/core/Easing

    虽然我建议在插值器上使用弹簧,尤其是模拟弹簧的插值器。弹簧会给人一个更自然的外观。 :)

    【讨论】:

      【解决方案2】:

      我们可以使用compose的spring animation来实现OvershootInterpolator。尽管我们无法为动画提供任何自定义持续时间,但我们可以使用 stiffness 属性控制动画的速度。

      我们可以将任何自定义float values 放入stiffness 属性。 androidx.compose.animation.core 当前默认提供 4 stiffness 常量值,即,

      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
          .....
      }
      
      

      我们可以检查哪个stiffness 适合我们的情况。

      例如:-(中速)

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

      我们还可以为stiffness 设置自定义值,例如:-

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

      您可以使用custom float values 调整刚度以达到理想的动画持续时间。

      【讨论】:

        猜你喜欢
        • 2014-05-08
        • 2014-06-12
        • 1970-01-01
        • 2022-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-20
        • 2018-07-10
        相关资源
        最近更新 更多