移动端跨平台动效工具Lottie, PAG的使用

发布时间 2023-07-24 18:43:30作者: 滴水微澜

动效工具Lottie
 
Lottie 是 Airbnb 开源的一套跨平台的完整的动画效果解决方案,设计师可以使用 Adobe After Effects 设计出漂亮的动画之后,使用 Lottic 提供的 Bodymovin 插件将设计好的动画导出成 JSON 格式,就可以直接运用在 iOS、Android、Web 和 React Native之上,无需其他额外操作。
从网络请求加载动画: Lottie 的一个优点是可以从网络请求加载动画。所以,应该将网络请求的响应内容转换为字符串格式。
Lottie 核心类
LottieAnimationView:继承自 AppCompatImageView,是加载 Lottie 动画的默认和最简单的方式。
LottieDrawable:具有大多数与 LottieAnimationView 相同的 API,因此可以在任何视图上使用它。

使用方法
func buildLOTAnimationView(_ resourceUrl: String) throws -> LOTAnimationView {
    //网络下载
    let lotView = try LOTAnimationView(contentsOf: URL(string: ""))
    //本地加载
    let zipPath = MyCache.cacheDataPath(for: resourceUrl)
    let lotView = try LOTAnimationView.animation(withFilePath: "\(zipPath!)/data.json", error: ())
    lotView.frame = UIScreen.main.bounds
    lotView.contentMode = .scaleAspectFill
    lotView.loopAnimation = true
    lotView.play()
    return lotView
}

动效工具PAG

PAG(Portable Animated Graphics)是腾讯自主研发的一套完整的动画工作流解决方案,助力于将 AE 动画方便快捷的应用于各平台终端。和 Lottie、SVGA 相比,支持的 AE 特性更多,支持的平台更广(增加了 mac OS、Windows 和 Linux),性能方面也做了深层次的优化,支持图层编辑,可以与视频编辑场景紧密结合
文件格式方面
Lottie 导出素材格式是 json 文本,可读性高,但是承载 AE 特性能力差,文件体积大,解码速度慢。SVGA 使用 ProtoBuffer 序列化,解码速度快,最终生成的文件直接使用 zip 压缩。PAG 采用二进制的编码方法,配套自研编解码器,动态比特位压缩,冗余信息极少,文件体积最小,解码速度最快,且支持图片和音频信息编码。
平台端支持方面
目前 Lottie 仅支持 Android、iOS、web、mac OS,SVGA 支持 Android、iOS 和 web 端,PAG 可以支持到 Android、iOS、web、mac OS、windows、Linux,涵盖到所有平台。

使用方法
//1.读取PAG素材文件, pagPath为pag动画的模版文件
pagFile = PAGFile.load(pagPath)

//2.替换模版资源
private func replacePag(image: UIImage, index: Int) {
    let pagImage = PAGImage.fromCGImage(image.cgImage)
    pagImage?.setScaleMode(PAGScaleModeZoom)
    pagFile?.replaceImage(Int32(index), data: pagImage)
}
private func replacePag(text: String, index: Int) {
    let pagText = pagFile?.getTextData(Int32(index))
    pagText?.text = text
    pagFile?.replaceText(Int32(index), data: pagText)
}

//3.创建PAG播放视图PAGView
self.pagView = PAGView.init(frame: self.view.bounds)
if let pagView = self.pagView {
    //关联PAGView和PAGFile
    pagView.setComposition(self.pagFile)
    pagView.setRepeatCount(0)
    pagView.setMaxFrameRate(30)
    pagView.setCacheScale(0.8)
}

 

参考文章:
https://juejin.cn/post/6844903661760413704
https://github.com/Tencent/libpag/blob/main/README.zh_CN.md
https://cloud.tencent.com/developer/inventory/25439/article/1935722