1. 程式人生 > >Android-動畫- Lottie 動畫庫使用介紹

Android-動畫- Lottie 動畫庫使用介紹

Lottie 是 Airbnb 公司開源的動畫庫。官方文件是這麼介紹的Lottie for Android, iOS, React Native, and Web。Lottie is a mobile library for Android and iOS that parses Adobe After Effects animations exported as json with Bodymovin and renders them natively on mobile and on the web!
很簡單就不解釋了.

在 Android 上使用

  • 在專案的 build.gradle
    檔案中新增如下內容
dependencies {
    ...
    compile 'com.airbnb.android:lottie:2.5.1'
    ...
}

如果你使用的 SDK 是 26 以上的版本,可以使用 lottie-android 中最新的版本

dependencies {
  implementation 'com.airbnb.android:lottie:2.5.5'
}

Tip:Lottie supports API 16 and above,僅支援 api 16 及以上版本

  • res/raw (lottie_rawRes) or assets/ (lottie_fileName)
    中存放json動畫檔案,在 xml 就可以直接使用了,如下:
<com.airbnb.lottie.LottieAnimationView
    android:id="@+id/animation_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    // json 動畫在 raw 資料夾下使用
    app:lottie_rawRes="@raw/hello_world"
    // json動畫在 assets 資料夾下使用
    app:lottie_fileName="hello_world.json"
// Loop indefinitely 設定無限迴圈 app:lottie_loop="true" // Start playing as soon as the animation is loaded 自動馬上載入 app:lottie_autoPlay="true" />
  • 如果你不想用 xml 實現,可以通過程式碼來實現,實現方式如下:
LottieAnimationView animationView = ...
// json 動畫在 raw 資料夾下使用
animationView.setAnimation(R.raw.hello_world);
// or json動畫在 assets 資料夾下使用
animationView.setAnimation(R.raw.hello_world.json);

animationView.playAnimation();
  • 如果不想本地存放動畫檔案,可以從網路讀取動畫檔案,下面是官方文件的使用介紹,但是不全。可以參考這篇文章的使用方式—-Lottie- 讓Android動畫實現更簡單
JsonReader jsonReader= new JsonReader(new StringReader(json.toString()))
animationView.setAnimation(jsonReader)
animationView.playAnimation
  • 使用 LottieComposition 去預載入動畫
LottieAnimationView animationView = ...;
 ...
 Cancellable compositionLoader = LottieComposition.Factory.fromJsonString(getResources(), jsonString, (composition) -> {
     animationView.setComposition(composition);
     animationView.playAnimation();
 });

 // Cancel to stop asynchronous loading of composition
 // compositionCancellable.cancel();
  • 動畫監聽
animationView.addAnimatorUpdateListener((animation) -> {
    // Do something.
});
animationView.playAnimation();
...
if (animationView.isAnimating()) {
    // Do something.
}
...
animationView.setProgress(0.5f);
...
  • 定製動畫速度和時常
// Custom animation speed or duration.
ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f);
animator.addUpdateListener(animation -> {
    animationView.setProgress(animation.getAnimatedValue());
});
animator.start();
  • 迴圈播放
    可以使用 setRepeatMode(...) or setRepeatCount(...)控制迴圈播放,或者你直接在 xml 中使用 lottie_loop="true"

更多詳細使用請參考官方文件
你可以直接下載 lottiefiles 裡面的動畫 直接使用