乐闻世界logo
搜索文章和话题

How to get total number of frames available in the Lottie Animation?

1个答案

1

When using Lottie Animation, retrieving the available frame count is a crucial feature, especially when you need precise control over animation playback or performing operations on specific frames. Lottie is a widely adopted library that renders animations exported from Adobe After Effects across multiple platforms. Retrieving the frame count of an animation can be achieved programmatically, depending on the platform you are using (such as Android, iOS, or Web).

For example, on Android:

  1. Initialize LottieAnimationView: First, you need an instance of LottieAnimationView, which is typically defined in your layout file (XML) or created programmatically.
xml
<com.airbnb.lottie.LottieAnimationView android:id="@+id/lottieAnimationView" android:layout_width="wrap_content" android:layout_height="wrap_content" app:lottie_fileName="animation.json"/>
  1. Load the Animation: Load the animation by specifying the animation file.
java
LottieAnimationView animationView = findViewById(R.id.lottieAnimationView); animationView.setAnimation("animation.json"); animationView.playAnimation();
  1. Retrieve the Frame Count: Use the getComposition() method from LottieDrawable to obtain a LottieComposition object, then query the total frame count using it.
java
if (animationView.getDrawable() instanceof LottieDrawable) { LottieDrawable lottieDrawable = (LottieDrawable) animationView.getDrawable(); LottieComposition composition = lottieDrawable.getComposition(); float frameRate = composition.getFrameRate(); float startFrame = composition.getStartFrame(); float endFrame = composition.getEndFrame(); float totalFrames = endFrame - startFrame; Log.d("LottieInfo", "Total frames: " + totalFrames + " at " + frameRate + " fps"); }

On iOS:

In iOS, you can use a similar approach by leveraging LOTAnimationView to retrieve the frame count.

swift
import Lottie let animationView = AnimationView(name: "animation") animationView.play() if let composition = animationView.animation { let totalFrames = composition.endFrame - composition.startFrame print("Total frames: \(totalFrames)") }

On Web:

For web applications, you can achieve similar functionality using the lottie-web library.

javascript
import lottie from 'lottie-web'; const animation = lottie.loadAnimation({ container: document.getElementById('lottie'), // the DOM element renderer: 'svg', loop: true, autoplay: true, path: 'animation.json' // the path to the animation JSON }); animation.addEventListener('DOMLoaded', function() { const totalFrames = animation.totalFrames; console.log("Total frames:", totalFrames); });

Through the above examples, retrieving the frame count of Lottie animations is straightforward and effective across any platform. This is highly beneficial for precise animation control, such as displaying specific information on certain frames or triggering other actions.

2024年7月20日 11:52 回复

你的答案