Lottie 动画
问题
Lottie 的原理和使用场景?
答案
什么是 Lottie
Lottie 是 Airbnb 开源的动画库,可以直接在 App 中播放 After Effects 导出的 JSON 动画。
After Effects → Bodymovin 插件导出 JSON → Lottie 渲染
使用
import Lottie
// UIKit
let animationView = LottieAnimationView(name: "loading")
animationView.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
animationView.loopMode = .loop
animationView.play()
view.addSubview(animationView)
// SwiftUI
struct LoadingView: View {
var body: some View {
LottieView(animation: .named("loading"))
.playing(loopMode: .loop)
.frame(width: 200, height: 200)
}
}
Lottie vs 其他方案
| 方案 | 适用场景 |
|---|---|
| UIView.animate | 简单位移、缩放、透明度 |
| Core Animation | 路径动画、关键帧 |
| Lottie | 复杂设计师动画(loading、引导页) |
| APNG/GIF | 简单帧动画(体积大) |
| SpriteKit | 游戏级粒子效果 |
常见面试问题
Q1: Lottie 的性能如何?
答案:Lottie 默认使用 Core Animation 渲染,性能较好。但复杂动画(大量形状、遮罩)可能造成 GPU 压力。可以使用 renderingEngine = .mainThread 切换为 CPU 渲染进行对比。