MT iOS

iOS使用Lottie展示.json格式的动图笔记

2022-06-28  本文已影响0人  数字d

新建一个iOS项目,cocopod导入lottie-ios

    pod 'lottie-ios'

本地json文件的读取和展示:文件太长从代码中获取吧,或者用远程地址下载

https://elinknft.oss-cn-hangzhou.aliyuncs.com/lottie/zy_lottie_live.json

控件的创建和本地文件的读取:

import UIKit
import Lottie

class ViewController: UIViewController {
    var animationView: AnimationView?
    override func viewDidLoad() {
        super.viewDidLoad()
  
        //打开注释展示本地coffee.json文件的效果
//        self.displayLocalJsonFileWithName(string: "coffee")
        
        //打开注释,展示远程地址下zy_lottie_live.json文件的效果
        self.displayUrlJsonFileWithUrl(urlString: "https://elinknft.oss-cn-hangzhou.aliyuncs.com/lottie/zy_lottie_live.json")
        
    }
    //展示本地的.json文件
    func displayLocalJsonFileWithName(string:String) {
        //初始化
        animationView = .init(name: string)
//        设置frame
        animationView!.frame = view.bounds
//        设置填充方式
        animationView!.contentMode = .scaleAspectFit
        animationView!.animationSpeed = 0.5
        view.addSubview(animationView!)
//        循环播放
        animationView!.loopMode = LottieLoopMode.loop
        animationView!.play()
    }
    
    //展示网络地址的json文件
    func displayUrlJsonFileWithUrl(urlString:String) {
        let url:URL = URL.init(string: urlString)!

        animationView = .init(url: url, imageProvider: nil, closure: { error in
                self.startDisplay()
        }, animationCache: nil)
        view.backgroundColor = .blue
    }
    
    
    //远程资源下的json文件需要执行完下载之后才能开始动画
    func startDisplay(){
        animationView!.frame = view.bounds
        // 3. Set animation content mode
        animationView!.contentMode = .scaleAspectFit
        // 4. Set animation loop mode
        // 5. Adjust animation speed
        animationView!.animationSpeed = 0.5
        view.addSubview(animationView!)
        // 6. Play animation
        animationView!.loopMode = LottieLoopMode.loop
        animationView!.play()
    }
}

在项目中使用的时候需要考虑到切后台和push到其他页面之后返回,这样的情况需要通过一个属性来保存当前播放状态,等到返回的时候做回复播放的操作,属性的默认值是pause暂停,使用pauseAndRestore会在返回到当前页面的时候恢复播放

        animationViewBg!.backgroundBehavior = .pauseAndRestore

展示出来的效果:
波浪:


wave.gif

咖啡:


coffee.gif

代码拉取地址:https://gitee.com/xgkp/lottietest.git

上一篇 下一篇

猜你喜欢

热点阅读