Swift加载Lottie

OC使用时,需要通过swift透出方法供OC使用

// 此处文件名可以从Build Settings下搜索Generated Header Name的值得出
#import <Test-Swift.h>

一、导入包

target 'iOS' do
  use_frameworks!
  
  # 此处
  pod 'lottie-ios'
end

二、功能实现

1. 创建组件

import Lottie

@objcMembers class LottieAnimView: UIView, UIScrollViewDelegate {
	static let sharedManager: LottieAnimView = LottieAnimView()
	private var lotView: AnimationView = AnimationView()
	
  func createLottieView(path: String) {
      let sp = path.components(separatedBy: ".")
      
      if let filePath = Bundle.main.path(forResource: sp.first!, ofType: "json") {
          let animation = Animation.filepath(filePath)
          lotView.animation = animation
      }
      
      // 修改fill方式
      lotView.contentMode = .scaleToFill
      
      // true:视图会使用旧版的 Autoresizing Mask 来进行布局。这意味着视图的位置和大小将根据其父视图的边界和自身的自动布局规则进行自动调整
      // false:视图将使用 Auto Layout 进行布局。这意味着你可以通过约束(constraints)来精确地定义视图的位置、大小和相对关系。
      // 如果不设置此处,则设置宽高无效。好像只有在动态修改frame时无效
      lotView.translatesAutoresizingMaskIntoConstraints = true
      
      lotView.loopMode = .loop
      
      lotView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
      
      // 添加点击事件
      let tapGesture = UITapGestureRecognizer(target: self, action: #selector(animationViewTapped))
      lotView.addGestureRecognizer(tapGesture)
      lotView.isUserInteractionEnabled = true
      
      // 此处根据需要添加到父级ViewController上
      UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(lotView)
    }
    
    @objc func animationViewTapped(sender: UITapGestureRecognizer) {
        // 可以根据sender.view获取AnimationView
        print("点击了AnimationView")
    }
}

2. 常用方法

// 1. 播放
lotView.play()

// 2. 暂停
lotView.pause()

// 3. 取消
lotView.stop()

三、注意

  1. 可以动态修改loopMode方式
  2. 我们的使用场景是在lua层先调用createLottieView,之后立马play,此时发现会动画卡在第一帧,怀疑是线程堵塞,在play之前让出CPU的时间片1个游戏帧即可

相关推荐

  1. SwiftLottie

    2024-04-25 07:20:03       39 阅读
  2. iOS swift5 网络图片的第三方框架

    2024-04-25 07:20:03       36 阅读
  3. Swift - swiftc

    2024-04-25 07:20:03       30 阅读
  4. 同步、异步、延迟、预的区别

    2024-04-25 07:20:03       64 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-25 07:20:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-25 07:20:03       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-25 07:20:03       87 阅读
  4. Python语言-面向对象

    2024-04-25 07:20:03       96 阅读

热门阅读

  1. 基于Promise + XHR 封装myAxios函数

    2024-04-25 07:20:03       39 阅读
  2. Flutter 项目添加 IOS 小组件开发记录

    2024-04-25 07:20:03       37 阅读
  3. linux命令之printf

    2024-04-25 07:20:03       37 阅读
  4. TCP详解

    TCP详解

    2024-04-25 07:20:03      31 阅读
  5. 【Altium Designer-画板指南】

    2024-04-25 07:20:03       32 阅读
  6. 骑砍2霸主MOD开发(8)-action_sets.xml骨骼动画

    2024-04-25 07:20:03       36 阅读
  7. elment-table实现行滚动效果

    2024-04-25 07:20:03       36 阅读