跳到主要内容

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 渲染进行对比。

相关链接