1. Lottie is introduced

Lottie is an open source, cross-platform, complete animation solution that allows designers to create beautiful animations using Adobe After Effects. Using Lottic’s Bodymovin plugin, you can export your designed animation to JSON format and use it directly on iOS, Android, The Web, and React Native without additional operations.

Lottie related Websites:

  • Lottie’s official website
  • Lottie on Github
  • Lottie for Android
  • Lottie for iOS
  • Lottie for Web
  • Lottie for React Native

2. Lottie use

Lottie supports Jellybean (API 16) and above. The simplest way to use it is to use LottieAnimationView directly, which inherits directly from AppCompatImageView.

2.1 Lottie rely on

Gradle is the only build configuration supported, so just add dependencies to your project’s build. Gradle file:

dependencies {
  implementation "com.airbnb.android:lottie:$lottieVersion"
}
Copy the code

The latest version is:

2.2 Lottie Core classes

  • LottieAnimationView: inherited fromAppCompatImageView, it is loadedLottieThe default and easiest way to animate.
  • LottieDrawable: has most withLottieAnimationViewThe sameAPI, so you can use it on any view.

2.3 Loading Animations

Lottie supports Jellybean (API 16) and above. Lottie Animation supports loading animations from the following locations:

  • src/main/res/rawJson animation in.
  • src/main/assetsJson file in.
  • src/main/assetsZip file in. For more information, seeimages docs.
  • Json or ZIP fileUrl.
  • Json string. A source can come from anything, including its own network stack.
  • Json file or ZIP fileInputStream.

2.3.1 Used in XML

The easiest way to use it is to use LottieAnimationView. Lottie supports loading animation resources from RES/RAW or Assets /. Res/RAW is recommended because you can use static references to animations through R files rather than just string names. This can also help build static analysis because it can track the use of animation.

The common properties and functions of LottieAnimationView are as follows:

attribute function
lottie_fileName Sets the name of the JSON file to play the animation
lottie_rawRes Set the JSON file resource to play the animation
lottie_autoPlay Sets whether the animation plays automatically (default: false)
lottie_loop Sets animation to loop (default: false)
lottie_repeatMode Set the animation repeat mode (default: restart)
lottie_repeatCount Sets the number of repetitions of the animation (default: -1)
lottie_cacheStrategy Set cache policy for animation (default weak)
lottie_colorFilter Sets the animation’s coloring color (lowest priority)
lottie_scale Set the animation scale (default: 1F)
lottie_progress Set the playback progress of the animation
lottie_imageAssetsFolder Sets the image resource file address that the animation depends on

Store the JSON file of the animation in RES/RAW (lottie_rawRes) or assets/ (lottie_fileName), and then use it directly in XML as follows:

<com.airbnb.lottie.LottieAnimationView
        android:id="@+id/animation_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        app:lottie_rawRes="@raw/hello_world"
        // or
        app:lottie_fileName="hello_world.json"

        app:lottie_loop="true"
        app:lottie_autoPlay="true" />
Copy the code

2.3.2 Used in code

The common methods and functions of LottieAnimationView are as follows:

methods function
setAnimation(String) Sets the name of the JSON file to play the animation
setAnimation(String, CacheStrategy) Set the JSON file resource and cache policy to play the animation
setAnimation(int) Sets the name of the JSON file to play the animation
setAnimation(int, CacheStrategy) Set the JSON file resource and cache policy to play the animation
loop(boolean) Sets animation to loop (default: false)
setRepeatMode(int) Set the animation repeat mode (default: restart)
setRepeatCount(int) Sets the number of repetitions of the animation (default: -1)
lottie_cacheStrategy Set cache policy for animation (default weak)
lottie_colorFilter Sets the animation’s coloring color (lowest priority)
setScale(float) Set the animation scale (default: 1F)
setProgress(float) Set the playback progress of the animation
setImageAssetsFolder(String) Sets the image resource file address that the animation depends on
playAnimation() Play the animation from the beginning
pauseAnimation() Pause animation
resumeAnimation() Continue playing the animation from the current location
cancelAnimation() Unplay the animation

If you don’t want to do it in XML, you can do it in code, either by loading native animation resources directly or by requesting animations from the web.

  • fromres/rawassets/Loading animation resources:
LottieAnimationView animationView = ...

animationView.setAnimation(R.raw.hello_world);
// or
animationView.setAnimation(R.raw.hello_world.json);

animationView.playAnimation();
Copy the code

This method loads the file in the background, parses the animation, and asynchronously starts rendering when it’s done.

  • Loading animations from a Web request: One advantage of Lottie is that animations can be loaded from a web request. Therefore, the response content of the network request should be converted to a string format. Lottie uses a streamable JSON deserializer to improve performance and memory utilization, so don’t convert it into your own JSONObject, which will only hurt performance.
LottieAnimationView animationView = ...
// This allows lottie to use the streaming deserializer mentioned above.
JsonReader jsonReader = new JsonReader(new StringReader(json.toString()));
animationView.setAnimation(jsonReader);
animationView.playAnimation();
Copy the code

2.4 Lottie’s cache policy

Your application may have some animations that are used frequently, such as loading animations and so on. To avoid the overhead of loading files and serialization each time, you can set a caching policy on your animations. All of the setAnimation APIs above can take the optional second parameter, CacheStrategy. By default, Lottie will save weak references to the animation, which should be sufficient for most cases. However, if you are certain that an animation will be used frequently, change its cache policy to cacheStrategy.strong; Or if you are sure that an animation is large and will not be used very often, change the cache policy to cacheStrategy.None.

CacheStrategy can be None, Weak, and Strong to allow LottieAnimationView to use Strong or Weak references to load and parse animations. Weak or strong indicates the combined GC reference strength in the cache.

2.5 Direct UseLottieDrawable

LottieAnimationView is a wrapped ImageView based on Lottie edrawable. All apis on LottieAnimationView are mirrored on LottieDrawable, so you can create your own instances and use drawable wherever you can use it, such as custom views or menus.

2.6 the use ofLottieCompositionGo to preload the animation

The supporting model for animation is Lotus Position. In most cases, setAnimation(…) is called on LottieAnimationView or LottieDrawable. That’s enough. However, if you want to preload an animation to make it immediately available, You can use LottieComposition. Factory API return can be set directly in LottieAnimationView or LottieDrawable LottieComposition object. Also, you usually don’t need to add the overhead of the management components yourself. The default cache in LottieAnimationView is sufficient for most use cases.

LottieAnimationView animationView = ... ; . Cancellable compositionLoader = LottieComposition.Factory.fromJsonString(getResources(), jsonString, (composition) -> { animationView.setComposition(composition); animationView.playAnimation(); });// Cancel to stop asynchronous loading of composition
 // compositionCancellable.cancel();
Copy the code

2.7 Animation Monitor

animationView.addAnimatorUpdateListener((animation) -> {
    // do something.}); animationView.playAnimation(); .if (animationView.isAnimating()) {
    // do something.}... animationView.setProgress(0.5 f); .Copy the code

In the update listener callback:

  • animation.getAnimatedValue()Returns the playback progress of the animation regardless of the current min/Max frame setting [0,1].
  • animation.getAnimatedFraction()Returns the playback progress of the animation, taking into account the set minFrame/maxFrame.

2.8 Control the speed and duration of Lottie animation execution

Although playAnimation() is sufficient for most use cases, setProgress(…) can be called in the update callback. Method to set the progress of your own animation.

// Custom animation speed or duration.
ValueAnimator animator = ValueAnimator.ofFloat(0f.1f); animator.addUpdateListener(animation -> { animationView.setProgress(animation.getAnimatedValue()); }); animator.start(); .Copy the code

2.9 Looping

SetRepeatMode (…) can be used as ValueAnimator. Or setRepeatCount (…). The lottie_loop method controls the playback of the animation, or you can start the loop directly in the XML using Lottie_loop =”true”.

2.10 Animation Size (PX vs DP)

Lottie converts all px values in After Effects to DPS on the device so that everything is rendered at the same size on the device. This means that instead of animating 1920×1080 in After Effects, it looks more like 411x731px in After Effects, which roughly corresponds to the DP screen size of most phones today.

However, if your animation is not the perfect size, you have two options:

2.10.1 ImageView scaleType

LottieAnimationView is a wrapped ImageView that supports centerCrop and centerInside, so you can use these two tool methods just like any other image.

2.10.2 Lottie setScale (…).

Both LottieAnimationView and LottieDrawable have setScale(float) apis that you can use to manually zoom in and out of animations. This is rarely useful, but can be used in certain situations.

If the animation is slow, be sure to check the performance documentation. However, you can try scaling animations using scaleType, which will reduce the amount of Lottie rendering per frame. This is especially useful if you have large masks and mattes.

2.11 Play animation segments

Playing/looping individual parts of an animation is often convenient. For example, the first half of an animation might be “on” and the second half “off.” LottieAnimationView and LottieDrawable have apis for controlling the current segment:

setMinFrame(...)

setMaxFrame(...)

setMinProgress(...)

setMaxProgress(...)

setMinAndMaxFrame(...)

setMinAndMaxProgress(...)
Copy the code

The loop API will follow the min/Max frames set here.

3. Principle introduction

3.1 Lottie Animation Json file structure

  1. The structure layer: can read the width and height of the animation canvas, frame number, background color, time, start key frame, end frame and other information.
  2. asset: Picture resource information collection, here is placed in the production of animation reference picture resources.
  3. layers: layer collection, how many layers can be obtained here, the start frame and end frame of each layer, etc.
  4. shapes: set of elements, you can get that each layer contains multiple animation elements.

3.2 Lottie Layered rendering principle

3.3 Lottie Animation operation flow chart

4. Preparation for use

4.1 Download and Install After Effects

Download address: www.adobe.com/cn/products…

4.2 Download and install Bodymovin

  1. If yes, turn off After Effects;

  2. Install ZXP Installer;

Download: aescripts.com/learn/zxp-i…

  1. Download the latest BodyMovin extension;

Download: github.com/airbnb/lott…

  1. Open the ZXP Installer and drag the BodyMovin extension into the window;

  2. Open up After Effects.

Under the “Window> Extensions” menu you should see “Bodymovin”

4.3 Lottiefiles sample application

Google Play
App Store

After you’ve done all three things, check out some overview of the workflow in the SVG/Sketch to Lottie walkthrough or Illustrator to Lottie Walkthrough.

5 LottieFiles

LottieFiles provides Lottie animations uploaded by many designers and provides preview effects, which can be directly downloaded into JSON or generated into a QR code, which can be scanned by Lottie App to see the effects.

LottieFiles:www.lottiefiles.com/

Lottie-editor:github.com/sonaye/lott…

LottieFiles itself already supports editing animations using Lottie-Editor. If you need to modify an animation, click Customize with Bodymovin Editor in the upper right corner of the animation preview interface to edit the animation directly.

6. Thanks

  1. airbnb.io/lottie
  2. Programmers also want to change Lottie animations? Yes!