# Compose 动画艺术探索之动画规格

1,534

``````interface AnimationSpec<T> {
fun <V : AnimationVector> vectorize(
converter: TwoWayConverter<T, V>
): VectorizedAnimationSpec<V>
}
``````

## 动画规格——Spring

`spring` 是很多动画的默认动画规格，比如前几篇文章中说到的 `animate*AsState``updateTransition` 的默认动画规格都是 `spring` 。下面来看下 `spring` 的源码吧！

``````@Stable
fun <T> spring(
dampingRatio: Float = Spring.DampingRatioNoBouncy,
stiffness: Float = Spring.StiffnessMedium,
visibilityThreshold: T? = null
): SpringSpec<T> =
SpringSpec(dampingRatio, stiffness, visibilityThreshold)
``````

• dampingRatio：阻尼比，默认值为 `DampingRatioNoBouncy` ，也就是无阻尼，通俗点说就是没有弹性，还有一些别的值，下面会一一列举
• stiffness：刚度，默认值为 `StiffnessMedium` ，中度，别的值也会在下面列举
• visibilityThreshold：可见性阈值

``````object Spring {
// 对于极硬的弹簧刚度常数
const val StiffnessHigh = 10_000f
​
// 中等硬度弹簧的刚度常数。这是弹簧力的默认刚度。
const val StiffnessMedium = 1500f
​
// 中低刚度弹簧的刚度常数。这是用于进入出口转换的弹簧的默认刚度。
const val StiffnessMediumLow = 400f
​
// 低刚度弹簧的刚度常数
const val StiffnessLow = 200f
​
// 很低刚度的弹簧的刚度常数
const val StiffnessVeryLow = 50f
​
// 弹性弹簧的阻尼比。注意:对于欠阻尼弹簧(即阻尼比< 1)，阻尼比越低，弹簧越有弹性。
const val DampingRatioHighBouncy = 0.2f
​
// 中等弹性弹簧的阻尼比。这也是弹簧力的默认阻尼比。
const val DampingRatioMediumBouncy = 0.5f
​
// 低弹性弹簧的阻尼比。
const val DampingRatioLowBouncy = 0.75f
​
// 无弹性弹簧的阻尼比
const val DampingRatioNoBouncy = 1f
​
// 基于物理的动画的默认截断，默认的位移阈值
const val DefaultDisplacementThreshold = 0.01f
}
``````

### 默认值无阻尼和中度刚度

``````val blue = remember { mutableStateOf(true) }
val color by animateColorAsState(
if (blue.value) Blue else Red,
animationSpec = spring(
dampingRatio = Spring.DampingRatioNoBouncy,
stiffness = Spring.StiffnessMedium
)
)
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Button(
onClick = { blue.value = !blue.value },
) {
Text("修改颜色值")
}
Box(modifier = Modifier.size(100.dp).background(color))
}
``````

### 默认值无阻尼和很低刚度

``````animationSpec = spring(
dampingRatio = Spring.DampingRatioNoBouncy,
stiffness = Spring.StiffnessVeryLow
)
``````

### 很低刚度和高阻尼

``````animationSpec = spring(
dampingRatio = Spring.DampingRatioHighBouncy,
stiffness = Spring.StiffnessVeryLow
)
``````

``````var isSmall by remember { mutableStateOf(true) }
val size: Dp by animateDpAsState(
targetValue = if (isSmall) 40.dp else 100.dp,
animationSpec = spring(
dampingRatio = Spring.DampingRatioHighBouncy,
stiffness = Spring.StiffnessVeryLow
)
)
``````

OK，改成了 `size` 咱们再来看下效果！

`size` 就能明显看到弹簧效果了！

## 动画规格——tween

`tween` 是用来创建使用给定的持续时间、延迟和缓和曲线配置的动画规格，先来看下使用方法吧：

``````var isSmall by remember { mutableStateOf(true) }
val size: Dp by animateDpAsState(
targetValue = if (isSmall) 40.dp else 100.dp,
animationSpec = tween()
)
​
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Button(
onClick = { isSmall = !isSmall },
) {
Text("修改Dp值")
}
Box(modifier = Modifier.size(size).background(Blue))
}
``````

``````fun <T> tween(
durationMillis: Int = DefaultDurationMillis,
delayMillis: Int = 0,
easing: Easing = FastOutSlowInEasing
): TweenSpec<T> = TweenSpec(durationMillis, delayMillis, easing)
``````

• durationMillis：动画持续时间，默认值为 `DefaultDurationMillis` ，300
• delayMillis：动画在启动前等待的时间，以毫秒为单位
• easing：用于在开始和结束之间插入的松弛曲线，默认值为 `FastOutSlowInEasing`

``````fun interface Easing {
fun transform(fraction: Float): Float
}
``````

`Easing` 中官方给了四种实现，来看下吧！

``````// 以静止开始和结束的元素使用这个标准缓动。他们快速加速，逐渐减速，以强调过渡的结束。这是最常见的方式。这相当于原生插值器FastOutSlowInInterpolator
val FastOutSlowInEasing: Easing = CubicBezierEasing(0.4f, 0.0f, 0.2f, 1.0f)
​
// 进入的元素使用减速缓和动画，以峰值速度(元素移动的最快点)开始过渡，并在静止时结束。这相当于原生插值器LinearOutSlowInInterpolator
val LinearOutSlowInEasing: Easing = CubicBezierEasing(0.0f, 0.0f, 0.2f, 1.0f)
​
// 退出屏幕的元素使用加速缓动，它们从静止开始，以峰值速度结束。这相当于原生中插值器 FastOutLinearInInterpolator
val FastOutLinearInEasing: Easing = CubicBezierEasing(0.4f, 0.0f, 1.0f, 1.0f)
​
// 线性，匀速
val LinearEasing: Easing = Easing { fraction -> fraction }
``````

### LinearEasing

``````animationSpec = tween(
durationMillis = 2000,
easing = LinearEasing
)
``````

### FastOutLinearInEasing

``````animationSpec = tween(
durationMillis = 2000,
easing = FastOutLinearInEasing
)
``````

### LinearOutSlowInEasing

``````animationSpec = tween(
durationMillis = 2000,
easing = LinearOutSlowInEasing
)
``````

### FastOutSlowInEasing

``````animationSpec = tween(
durationMillis = 2000,
easing = FastOutSlowInEasing
)
``````

## 动画规格——snap

`Snap` 用于立即将动画值切换到结束值，先来看下 `snap` 的代码吧：

``````fun <T> snap(delayMillis: Int = 0) = SnapSpec<T>(delayMillis)
``````

``````class SnapSpec<T>(val delay: Int = 0) : DurationBasedAnimationSpec<T> {
override fun <V : AnimationVector> vectorize(
converter: TwoWayConverter<T, V>
): VectorizedDurationBasedAnimationSpec<V> = VectorizedSnapSpec(delay)
}
``````

``````interface DurationBasedAnimationSpec<T> : FiniteAnimationSpec<T> {
override fun <V : AnimationVector> vectorize(converter: TwoWayConverter<T, V>):
VectorizedDurationBasedAnimationSpec<V>
}
``````

``````val size: Dp by animateDpAsState(
targetValue = if (isSmall) 40.dp else 100.dp,
animationSpec = snap(delayMillis = 500)
)
``````

## 动画规格——keyframes

`keyframes` 基于动画持续时间中不同时间戳定义的值（即不同的关键帧）来制作动画。每个关键帧都可以使用 `KeyframesSpecConfig.at`来进行定义。老规矩，先来看下 `keyframes` 函数：

``````fun <T> keyframes(
init: KeyframesSpec.KeyframesSpecConfig<T>.() -> Unit
): KeyframesSpec<T> {
return KeyframesSpec(KeyframesSpec.KeyframesSpecConfig<T>().apply(init))
}
``````

``````class KeyframesSpecConfig<T> {
// 动画持续时间，默认为300
var durationMillis: Int = DefaultDurationMillis
​
// 动画播放延迟时间，默认为0
var delayMillis: Int = 0
​
// 关键帧
internal val keyframes = mutableMapOf<Int, KeyframeEntity<T>>()
​
// 添加一个关键帧
infix fun T.at(/*@IntRange(from = 0)*/ timeStamp: Int): KeyframeEntity<T> {
return KeyframeEntity(this).also {
keyframes[timeStamp] = it
}
}
​
// 为刚提供的时间戳开始的时间间隔添加 Easing
infix fun KeyframeEntity<T>.with(easing: Easing) {
this.easing = easing
}
}
``````

`KeyframesSpecConfig` 是一个泛型类，类中只有三个参数和两个方法，注释写在了代码中。但这块还需要说下 `kotlin` 的一个关键字 `infix``infix` 是中缀表达式，有几个前提条件：

• 必须是成员函数或扩展函数
• 必须只有一个参数
• 参数不可能是可变参数或默认参数

``````animationSpec =  keyframes {
durationMillis = 375
50.dp at 0 with LinearOutSlowInEasing
52.dp at 35 with FastOutLinearInEasing
55.dp at 75 // ms
100.dp at 225 // ms
}
``````

## 动画规格——repeatable

`repeatable` 用来构建可重复的动画，先来看下调用函数吧：

``````fun <T> repeatable(
iterations: Int,
animation: DurationBasedAnimationSpec<T>,
repeatMode: RepeatMode = RepeatMode.Restart,
initialStartOffset: StartOffset = StartOffset(0)
): RepeatableSpec<T> =
RepeatableSpec(iterations, animation, repeatMode, initialStartOffset)
``````

• iterations：重复次数，理论上来说应该大于一，其实等于也可以，但没必要
• animation：将被重复的动画规格，注意这里的动画规格是 `DurationBasedAnimationSpec` ，也就是说可以使用 `KeyframesSpec``SnapSpec``TweenSpec`
• repeatMode：指定动画播放模式
• initialStartOffset：动画开始的偏移

``````enum class RepeatMode {
// 将重新启动动画，并从开始值动画到结束值。
Restart,
​
// 将在动画重复时反转上一次迭代
Reverse
}
``````

`RepeatMode` 是一个枚举类，定义了两种类型 `Restart``Reverse``Restart` 将重新启动动画，并从开始值动画到结束值；`Reverse` 将在动画重复时反转上一次迭代。

``````value class StartOffsetType private constructor(internal val value: Int) {
companion object {
// 延迟动画的开始。
val Delay = StartOffsetType(-1)
​
// 快进动画到给定的播放时间，并立即开始播放。
val FastForward = StartOffsetType(1)
}
}
``````

``````val size: Dp by animateDpAsState(
targetValue = if (isSmall) 40.dp else 100.dp,
animationSpec = repeatable(iterations = 3, animation = tween(500))
)
``````

## 动画规格——infiniteRepeatable

``````fun <T> infiniteRepeatable(
animation: DurationBasedAnimationSpec<T>,
repeatMode: RepeatMode = RepeatMode.Restart,
initialStartOffset: StartOffset = StartOffset(0)
): InfiniteRepeatableSpec<T> =
InfiniteRepeatableSpec(animation, repeatMode, initialStartOffset)
``````

``````val size: Dp by animateDpAsState(
targetValue = if (isSmall) 40.dp else 100.dp,
animationSpec = infiniteRepeatable(animation = tween(500))
)
``````

## 总结

`FloatSpringSpec``FloatTweenSpec` 这两个动画规格比较特殊，系统没有提供直接进行使用的方法，其实也没有必要使用了，需要使用的话有 `spring``tween` 就够了。