# 4.6 动画原理


<br>


<br>

# Animatable 协议

我们之所以能看见动画的效果，是因为 SwiftUI 在视图变化的首尾状态之间不断地重绘视图，一系列静态视图因“视觉暂留”作用而造成一种连续的视觉印象，让我们感觉视图动起来了，这其实也是电影的原理。比如一个视图需要从透明度 0 变成 1，SwiftUI 会在 0 和 1 之间不断地作插值运算，不断重绘不同透明度的视图（0，0.1，0.2，0.3 ... 1.0），直到视图不再变化。如果使用 `.linear` 指定动画效果，那么视图的重绘过程是匀速的，如果使用 `.easeOut`，那么重绘的过程是先快后慢，以此类推。

SwiftUI 通过 [Animatable](https://developer.apple.com/documentation/swiftui/animatable) 协议定义视图该如何动画，它的声明如下：

```swift
public protocol Animatable {

    /// The type defining the data to animate.
    associatedtype AnimatableData : VectorArithmetic

    /// The data to animate.
    var animatableData: Self.AnimatableData { get set }
}
```

该协议只有一个关联类型的属性 `animatableData`，正是它告诉视图该如何去做动画。SwiftUI 中的各种形状、布局都已经实现该协议，所以我们能够使用动画流畅地改变形状、切换布局等。

<span style="background: #007BFF; color: white; padding: 3px 10px; border-radius: 5px">> 查看示例</span>

示例中自定义了一个曲线形状 Line1，通过参数 yFactor 线条的弯曲程度：

```swift
fileprivate struct Line1: Shape {
  var controYFactor: Double = 0
  
  func path(in rect: CGRect) -> Path {
    var path = Path()
    path.move(to: .init(x: 0, y: rect.midY))
    path.addQuadCurve(
      to: .init(x: rect.maxX, y: rect.midY),
      control: .init(x: rect.midX, y: rect.midY * controYFactor)
    )
    return path
  }
}
```

我们期望给它一个弹性动画：

```swift
@State private var l1_controlYFactor = 0.0

Line1(controYFactor: l1_controlYFactor)
  .stroke(.blue, style: strokeStyle)

Button("Update") {
  withAnimation(
    .spring(response: 0.3, dampingFraction: 0.3)
  ) {
    l1_controlYFactor = .random(in: 0...2)
  }
}
```

然后事与愿违，因为 SwiftUI 不知道该如何给 Line1 视图做重绘，我们得通过 Animatable 协议告诉它该给哪些数据做插值运算。

Shape 本身已经实现 Animatable 协议，其默认的 animatableData 属性是 [EmptyAnimatableData](https://developer.apple.com/documentation/swiftui/emptyanimatabledata) 实例，表示没有可动画的 animatableData 属性。

我们现在需要使曲线动起来，关键就是实现 Animatable 协议，使 controYFactor 成为可动画的数据：

```swift
var animatableData: Double {
  get { controYFactor }
  set { controYFactor = newValue }
}
```

当改变 controYFactor 参数时，SwiftUI 会在旧值和新值之间作插值运算，不断地调用 get 和 set 方法，驱动视图的更新，动画的效果就出来了。

# 多个动画数据

## AnimatablePair

Anmatable 协议中的 anmatableData 是关联类型：

```swift
associatedtype AnimatableData : VectorArithmetic
```

[VectorArithmetic](https://developer.apple.com/documentation/swiftui/vectorarithmetic) 是一个用于向量计算的协议，它继承自支持加减法的协议 [AdditiveArithmetic](https://developer.apple.com/documentation/swift/additivearithmetic) 。anmatableData 必须实现这两个协议，SwiftUI 才知道如何进行插值计算。

Swfit 中的基础数据类型如整形、浮点型已实现 AdditiveArithmetic 协议，上面示例中的动画数据 controYFactor 就是浮点型，它已经实现了相应的协议。

但 controYFactor 是一个单一的可动画数据，如果现在想在这个基础上同时改变线条的两个端点在 y 轴上的位置。可以使用内置的结构体 [AnimatablePair](https://developer.apple.com/documentation/swiftui/animatablepair) ，它已经实现了 VectorArithmetic 和 AdditiveArithmetic 协议，我们只需要将两个变量简单包装一下即可。

```swift
fileprivate struct Line2: Shape {
  var controYFactor = 0.0
  var pointYFactor = 0.0
  
  var animatableData: AnimatablePair<Double, Double> {
    get {
      .init(controYFactor, pointYFactor)
    }
    set {
      controYFactor = newValue.first
      pointYFactor = newValue.second
    }
  }
  
  func path(in rect: CGRect) -> Path {
    var path = Path()
    path.move(to: .init(x: 0, y: rect.maxY * pointYFactor))
    path.addQuadCurve(
      to: .init(x: rect.maxX, y: rect.maxY * pointYFactor),
      control: .init(x: rect.midX, y: rect.midY * controYFactor)
    )
    return path
  }
}
```

## 自定义可动画数据

AnimatablePair 虽然使用方便但有局限性，它只适合比较简单的可动画数据。假设需要在 Line2 的基础上再添加一个可动画变量，AnimatablePair 虽然也可以实现，但显得乏力：

```swift
var controYFactor: Double
var pointYFactor: Double
var pointXFactor: Double

var animatableData: AnimatablePair<
  Double,
  AnimatablePair<Double, Double>
> {
  get {
    .init(controYFactor, .init(pointYFactor, pointXFactor))
  }
  set {
    controYFactor = newValue.first
    pointYFactor = newValue.second.first
    pointXFactor = newValue.second.second
  }
}
```

更好的做法是将变量包装成一个结构体，将其作为可动画数据：

```swift
fileprivate struct Line3: Shape {
  var lineData: LineData
  
  var animatableData: LineData {
    get { lineData }
    set { lineData = newValue }
  }
  
  func path(in rect: CGRect) -> Path {
    var path = Path()
    path.move(to: .init(
      x: rect.maxX * lineData.pointXFactor,
      y: rect.maxY * lineData.pointYFactor)
    )
    path.addQuadCurve(
      to: .init(
        x: rect.maxX * (1 - lineData.pointXFactor),
        y: rect.maxY * lineData.pointYFactor
      ),
      control: .init(
        x: rect.midX,
        y: rect.midY * lineData.controYFactor
      )
    )
    return path
  }
}
```

LineData 需要实现 VectorArithmetic 协议后，SwiftUI 才知道如何进行插值计算：

```swift
struct LineData: VectorArithmetic {
  var controYFactor: Double
  var pointYFactor: Double
  var pointXFactor: Double
  
  static func + (lhs: Self, rhs: Self) -> Self {
    .init(
      controYFactor: lhs.controYFactor + rhs.controYFactor,
      pointYFactor: lhs.pointYFactor + rhs.pointYFactor,
      pointXFactor: lhs.pointXFactor + rhs.pointXFactor
    )
  }
  
  static func - (lhs: Self, rhs: Self) -> Self {
    .init(
      controYFactor: lhs.controYFactor - rhs.controYFactor,
      pointYFactor: lhs.pointYFactor - rhs.pointYFactor,
      pointXFactor: lhs.pointXFactor - rhs.pointXFactor
    )
  }
  
  static var zero: LineData {
    .init(controYFactor: 0, pointYFactor: 0, pointXFactor: 0)
  }
  
  var magnitudeSquared: Double {
    1.0
  }
  
  mutating func scale(by rhs: Double) {
    controYFactor.scale(by: rhs)
    pointYFactor.scale(by: rhs)
    pointXFactor.scale(by: rhs)
  }
}
```

# 小结

动画其实是状态数据变化时，SwiftUI 在首尾状态之间不停地作插值运算，生成一系列重绘的视图。并非所有的数据是可动画的，只有实现了 VectorArithmetic 协议的数据才能让 SwiftUI 知道如何进行插值运算。Swift 中的基础数据类型如整形、浮点型，已经实现相应的协议，可以直接作为可动画数据。对于自定义数据类型，需要实现 VectorArithmetic 协议，才能实现动画效果。



---

> 作者: 宋明  
> URL: https://apolla.cc/posts/4.6-%E5%8A%A8%E7%94%BB%E5%8E%9F%E7%90%86/  

