iOS LottieAnimationView 使用——加载、播放、控制
基本用法
import Lottie
class ViewController: UIViewController {
var animationView: LottieAnimationView!
override func viewDidLoad() {
super.viewDidLoad()
// 创建动画视图
animationView = LottieAnimationView(name: "loading") // loading.json
animationView.frame = CGRect(x: 100, y: 200, width: 200, height: 200)
animationView.center = self.view.center
// 设置播放参数
animationView.loopMode = .loop // .loop 无限 / .playOnce / .repeat(3) / .autoReverse
animationView.animationSpeed = 1.5 // 倍速
animationView.isUserInteractionEnabled = false
self.view.addSubview(animationView)
// 开始播放
animationView.play()
}
}
三种加载方式
// 方式一:Bundle 内文件(从项目 Bundle 加载 loading.json)
let anim1 = LottieAnimationView(name: "loading")
// 方式二:远程 URL
let url = URL(string: "你的 CDN 托管地址")!
let anim2 = LottieAnimationView(url: url)
// 方式三:直接传 Data
let data = try! Data(contentsOf: Bundle.main.url(forResource: "loading", withExtension: "json")!)
let anim3 = LottieAnimationView(data: data)
// 方式四:dotLottie 文件
let anim4 = LottieAnimationView(dotLottieName: "loading")
播放控制
// 播放
animationView.play()
// 暂停
animationView.pause()
// 停止并回到起始帧
animationView.stop()
// 跳到指定帧
animationView.currentFrame = 30
// 跳到指定进度(0~1)
animationView.currentProgress = 0.5
// 循环模式
animationView.loopMode = .loop // 无限循环
animationView.loopMode = .playOnce // 单次播放
animationView.loopMode = .repeat(3) // 播放 3 次
animationView.loopMode = .autoReverse // 来回自动反转
// 倍速(支持负数 = 反向播放)
animationView.animationSpeed = -1.0
// 播放指定帧范围
animationView.play(fromFrame: 10, toFrame: 30)
回调监听
iOS 端用闭包(Closure)实现回调:
animationView.play(
fromFrame: 0,
toFrame: nil,
loopMode: .loop,
completion: { finished in
if finished {
// 播放自然结束
} else {
// 被 stop() / pause() 打断
}
}
)
// 或者监听每一帧的变化
animationView.addAnimationObserver(self)
// 实现 LottieAnimationViewDelegate
extension ViewController: LottieAnimationViewDelegate {
func animationView(_ animationView: LottieAnimationView, didPlayFrame frame: CGFloat) {
// 每一帧都会调,谨慎使用
}
func animationViewDidFinish(_ animationView: LottieAnimationView) {
// 播放完成
}
}
SwiftUI 里使用
Lottie 提供了 SwiftUI 封装:
import Lottie
struct ContentView: View {
var body: some View {
LottieView(animation: .named("loading"))
.playbackMode(.playing(.toProgress(1, loopMode: .loop)))
.animationSpeed(1.0)
.frame(width: 200, height: 200)
}
}