iOS Lottie 使用 JSON
 {
animationView.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
animationView.center = view.center
animationView.loopMode = .loop
view.addSubview(animationView)
animationView.play()
}
Here, we create an AnimationView
instance with the name of the JSON file (without the file extension). We set the view's frame and center it in the parent view. We also set the loop mode to .loop
so the animation continues to play indefinitely. Finally, we add the animation view to the parent view and start playback.
远程加载
To load a Lottie animation from a remote server, you need to download the JSON file first. You can use libraries like Alamofire or URLSession to handle the download process. Once you have the JSON data, you can create an Animation
object and set it as the animation view's animation
property. Here's an example:
let animationURL = URL(string: "
URLSession.shared.dataTask(with: animationURL) { (data, response, error) in
guard let data = data else {
return
}
let animation = try? JSONDecoder().decode(Animation.self, from: data)
DispatchQueue.main.async {
if let animationView = AnimationView(animation: animation) {
animationView.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
animationView.center = self.view.center
animationView.loopMode = .loop
self.view.addSubview(animationView)
animationView.play()
}
}
}.resume()
In this code snippet, we use URLSession
to download the JSON data from a remote server. Once the data is downloaded, we decode it into an Animation
object using JSONDecoder
. We then create an AnimationView
instance with the animation object and add it to the parent view.
控制动画播放
Lottie provides several methods and properties to control the playback of animations.
暂停和继续播放
You can pause and resume the animation using the pause()
and play()
methods, respectively. For example:
animationView.pause()
animationView.play()
指定播放范围
You can specify the start and end frames of the animation to play only a portion of it. Use the currentProgress
property to set the playback progress. The value should be a fraction between 0 and 1. For example, to play the first half of the animation:
animationView.currentProgress = 0.5
动画速度
You can control the speed of the animation using the animationSpeed
property. The default value is 1.0, which represents normal playback