1. 程式人生 > >這樣做動畫互動,一點都不費力

這樣做動畫互動,一點都不費力

本文由雲+社群發表

作者:paulzeng

**導語:**Lottie是Airbnb開源的一個面向 iOS、Android、React Native 的動畫庫,可實現非常複雜的動畫,使用也及其簡單,極大釋放人力,值得一試。

一、簡介

Lottie 是Airbnb開源的一個面向 iOS、Android、React Native 的動畫庫,能分析 Adobe After Effects 匯出的動畫,並且能讓原生 App 像使用靜態素材一樣使用這些動畫,完美實現動畫效果。

現在使用各平臺的 native 程式碼實現一套複雜的動畫是一件很困難並且耗時的事,我們需要為不同尺寸的螢幕載入不同的素材資源,還需要寫大量難維護的程式碼,而Lottie可以做到同一個動畫檔案在不同平臺上實現相同的效果,極大減少開發時間,實現不同的動畫,只需要設定不同的動畫檔案即可,極大減少開發和維護成本。

官方效果圖:

img

img

二、如何使用

Lottie支援多平臺,使用同一個JSON動畫檔案,可在不同平臺實現相同的效果。

Android 通過Airbnb的開源專案lottie-android實現,最低支援 API 16;

IOS 通過Airbnb的開源專案lottie-ios實現,最低支援 IOS 7;

React Native,通過Airbnb的開源專案lottie-react-native實現;

img

這是React logo的動畫,以下以Android平臺為例如何使用Lottie

1.下載Lottie

在專案的 build.gradle 檔案新增依賴


<code class="language-js">dependencies {  
  compile 'com.airbnb.android:lottie:2.1.0'
}

2.新增 Adobe After Effects 匯出的動畫檔案

Lottie預設讀取Assets中的檔案,我們需要把動畫檔案react.json 儲存在app/src/main/assets檔案裡。(檔案比較大,只展示了部分內容,檔案連結


<code class="language-js">{
    &quot;v&quot;: &quot;4.6.0&quot;, 
    &quot;fr&quot;: 29.9700012207031, 
    &quot;ip&quot;: 0, 
    &quot;op&quot;: 141.000005743048, 
    &quot;w&quot;: 800, 
    &quot;h&quot;: 800, 
    &quot;ddd&quot;: 0, 
    &quot;assets&quot;: [ ], 
    &quot;layers&quot;: [
        {
            &quot;ddd&quot;: 0, 
            &quot;ind&quot;: 0, 
            &quot;ty&quot;: 4, 
            &quot;nm&quot;: &quot;center_circle&quot;, 
            &quot;ks&quot;: {...}, 
            &quot;ao&quot;: 0, 
            &quot;shapes&quot;: [...], 
            &quot;ip&quot;: 0, 
            &quot;op&quot;: 900.000036657751, 
            &quot;st&quot;: 0, 
            &quot;bm&quot;: 0, 
            &quot;sr&quot;: 1
        }, 
        {...}, 
        {...}, 
        {...}
    ]
}

3.使用Lottie

在佈局檔案中直接新增Lottie的LottieAnimationView控制元件,即可在介面顯示React logo動畫效果


<code class="language-js">&lt;com.airbnb.lottie.LottieAnimationView
        android:id=&quot;@+id/animation_view&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        app:lottie_fileName=&quot;react.json&quot;
        app:lottie_loop=&quot;true&quot;
        app:lottie_autoPlay=&quot;true&quot; /&gt;

4.引入Lottie影響

(1)相容性

Lottie 最低支援版本API 16,低版本系統需要做降級動畫或者不展示動畫

(2)安裝包

影響項 使用前 使用後 結論
方法數 144807 145891 增加1084個方法
安裝包大小 41969KB 42037KB 增大68KB

這是用全民K歌release包的測試資料,lottie本身方法數不小,有方法數超標和安裝包過大的風險,業務可自行評估

注:LottieAnimationView繼承於V7的AppCompatImageView,需要引入V7相容包,根據業務需要,可以原始碼引入Lottie,讓LottieAnimationView繼承與ImageView,就不用引入V7相容包,可減小安裝大小。

三、使用小技巧

1.載入SDCard動畫檔案


<code class="language-js">StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(JSON_PATH + &quot;react.json&quot;)));
String content = null;
while ((content = bufferedReader.readLine()) != null){
    stringBuilder.append(content);
}
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
animationView.setAnimation(jsonObject);
animationView.loop(true);
animationView.playAnimation();

2.載入SDCard圖片


<code class="language-js">animationView.setImageAssetDelegate(new ImageAssetDelegate() {
    @Override
    public Bitmap fetchBitmap(LottieImageAsset asset) {
        try {
            FileInputStream fileInputStream = new FileInputStream(IMAGE_PATH + asset.getFileName());
            return BitmapFactory.decodeStream(fileInputStream);  ///把流轉化為Bitmap圖片
        } catch (Exception e) {
            Log.e(TAG, &quot;&quot;, e);
        }
        return null;
    }
});

3.載入SDCard字型


<code class="language-js">animationView.setFontAssetDelegate(new FontAssetDelegate(){
    public Typeface fetchFont(String fontFamily) {
        Typeface customFont = Typeface.createFromFile(FONT_PATH + fontFamily);
        return customFont;
    }
});

4.快取動畫


<code class="language-js">/*
* Lottie內部有兩個快取map(強引用快取,弱引用快取),在動畫檔案載入完成後會根據設定的快取策略快取動畫,方便下次使用。
*/
animationView.setAnimation(animation, LottieAnimationView.CacheStrategy.Strong);    //強快取

animationView.setAnimation(animation, LottieAnimationView.CacheStrategy.Weak);      //弱快取

四、Lottie實現原理

img

設計師把一張複雜的圖片使用多個圖層來表示,每個圖層展示一部分內容,圖層中的內容也可以拆分為多個元素。拆分元素之後,根據動畫需求,可以單獨對圖層或者圖層中的元素做平移、旋轉、收縮等動畫。

Lottie的使用的資源是需要先通過bodymovin( bodymovin 外掛本身是用於網頁上呈現各種AE效果的一個開源庫)將 Adobe After Effects (AE)生成的aep動畫工程檔案轉換為通用的json格式描述檔案。Lottie則負責解析動畫的資料,計算每個動畫在某個時間點的狀態,準確地繪製到螢幕上。

匯出的json動畫描述檔案:


<code class="language-js">{
    &quot;v&quot;: &quot;4.6.0&quot;, 
    &quot;fr&quot;: 29.9700012207031, 
    &quot;ip&quot;: 0, 
    &quot;op&quot;: 141.000005743048, 
    &quot;w&quot;: 800, 
    &quot;h&quot;: 800, 
    &quot;ddd&quot;: 0, 
    &quot;assets&quot;: [ ], 
    &quot;layers&quot;: [
        {...}, 
    ]
}

Lottie主要類圖:

img

圖:lottie_class

Lottie對外通過控制元件LottieAnimationView暴露介面,控制動畫。

LottieAnimationView繼承自ImageView,通過當前時間繪製canvas顯示到介面上。這裡有兩個關鍵類:LottieComposition 負責解析json描述檔案,把json內容轉成Java資料物件;LottieDrawable負責繪製,把LottieComposition轉成的資料物件繪製成drawable顯示到View上。順序如下:

img

1.json檔案解析

LottieComposition負責解析json檔案,建立資料到java物件的對映關係。

(1)解析json外部結構

LottieComposition封裝整個動畫的資訊,包括動畫大小,動畫時長,幀率,用到的圖片,字型,圖層等等。

json外部結構


<code class="language-js">{
    &quot;v&quot;: &quot;4.6.0&quot;,               //bodymovin的版本
    &quot;fr&quot;: 29.9700012207031,     //幀率
    &quot;ip&quot;: 0,                    //起始關鍵幀
    &quot;op&quot;: 141.000005743048,     //結束關鍵幀
    &quot;w&quot;: 800,                   //動畫寬度
    &quot;h&quot;: 800,                   //動畫高度
    &quot;ddd&quot;: 0, 
    &quot;assets&quot;: [...]             //資源資訊
    &quot;layers&quot;: [...]             //圖層資訊
}
//解析json的原始碼
static LottieComposition fromJsonSync(Resources res, JSONObject json) {
      Rect bounds = null;
      float scale = res.getDisplayMetrics().density;
      int width = json.optInt(&quot;w&quot;, -1);
      int height = json.optInt(&quot;h&quot;, -1);

      if (width != -1 &amp;&amp; height != -1) {
        int scaledWidth = (int) (width * scale);
        int scaledHeight = (int) (height * scale);
        bounds = new Rect(0, 0, scaledWidth, scaledHeight);
      }

      long startFrame = json.optLong(&quot;ip&quot;, 0);
      long endFrame = json.optLong(&quot;op&quot;, 0);
      float frameRate = (float) json.optDouble(&quot;fr&quot;, 0);
      String version = json.optString(&quot;v&quot;);
      String[] versions = version.split(&quot;[.]&quot;);
      int major = Integer.parseInt(versions[0]);
      int minor = Integer.parseInt(versions[1]);
      int patch = Integer.parseInt(versions[2]);
      LottieComposition composition = new LottieComposition(
          bounds, startFrame, endFrame, frameRate, scale, major, minor, patch);
      JSONArray assetsJson = json.optJSONArray(&quot;assets&quot;);
      parseImages(assetsJson, composition); //解析圖片
      parsePrecomps(assetsJson, composition);
      parseFonts(json.optJSONObject(&quot;fonts&quot;), composition); //解析字型
      parseChars(json.optJSONArray(&quot;chars&quot;), composition);  //解析字元
      parseLayers(json, composition);   //解析圖層
      return composition;
    }

(2)解析圖片資源


<code class="language-js">LottieImageAsset類封裝圖片資訊

&quot;assets&quot;: [                 //資源資訊
    {                       //第一張圖片
        &quot;id&quot;: &quot;image_0&quot;,    //圖片id
        &quot;w&quot;: 58,            //圖片寬度
        &quot;h&quot;: 31,            //圖片高度
        &quot;u&quot;: &quot;images/&quot;,     //圖片路徑
        &quot;p&quot;: &quot;img_0.png&quot;    //圖片名稱
    },
    {...}                   //第n張圖片
]
static LottieImageAsset newInstance(JSONObject imageJson) {
    return new LottieImageAsset(imageJson.optInt(&quot;w&quot;), imageJson.optInt(&quot;h&quot;), imageJson.optString(&quot;id&quot;),
          imageJson.optString(&quot;p&quot;));
}

(3)解析圖層

Layer封裝圖層資訊,現在lottie只支援PreComp,Solid,Image,Null,Shape,Text這6中圖層。


<code class="language-js">&quot;layers&quot;: [                 //圖層資訊
    {                       //第一層動畫
        &quot;ddd&quot;: 0, 
        &quot;ind&quot;: 0,           //layer id 圖層 id
        &quot;ty&quot;: 4,            //圖層型別
        &quot;nm&quot;: &quot;center_circle&quot;, 
        &quot;ks&quot;: {...},        //動畫
        &quot;ao&quot;: 0, 
        &quot;shapes&quot;: [...], 
        &quot;ip&quot;: 0,            //inFrame 該圖層起始關鍵幀
        &quot;op&quot;: 90,           //outFrame 該圖層結束關鍵幀
        &quot;st&quot;: 0,            //startFrame 開始
        &quot;bm&quot;: 0, 
        &quot;sr&quot;: 1
    }, 
    {...}                   //第n層動畫
]

2.如何動起來

Lottie時序圖:

img

利用屬性動畫控制進度,每次進度改變通知到每一層,觸發LottieAnimationView重繪。

(1)利用屬性動畫計算進度

這裡用到了屬性動畫來產生一個0~1的插值,根據不同的插值來設定當前動畫進度。

程式碼如下:


<code class="language-js">public LottieDrawable() {
    animator.setRepeatCount(0);
    animator.setInterpolator(new LinearInterpolator());
    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            if (systemAnimationsAreDisabled) {
                animator.cancel();
                setProgress(1f);
            } else {
                setProgress((float) animation.getAnimatedValue());
            }
        }
    });
}

(2)通過CompositionLayer把進度傳遞到各個圖層


<code class="language-js">@Override
public void setProgress(@FloatRange(from = 0f, to = 1f) float progress) {
    super.setProgress(progress);
    if (timeRemapping != null) {
        long duration = lottieDrawable.getComposition().getDuration();
        long remappedTime = (long) (timeRemapping.getValue() * 1000);
        progress = remappedTime / (float) duration;
    }
    if (layerModel.getTimeStretch() != 0) {
        progress /= layerModel.getTimeStretch();
    }
    progress -= layerModel.getStartProgress();
    for (int i = layers.size() - 1; i &gt;= 0; i--) {
        layers.get(i).setProgress(progress);
    }
}

(3)通知進度改變


<code class="language-js">  void setProgress(@FloatRange(from = 0f, to = 1f) float progress) {
    if (progress &lt; getStartDelayProgress()) {
      progress = 0f;
    } else if (progress &gt; getEndProgress()) {
      progress = 1f;
    }

    if (progress == this.progress) {
      return;
    }
    this.progress = progress;

    for (int i = 0; i &lt; listeners.size(); i++) {
      listeners.get(i).onValueChanged();
    }
  }

(4)最終回撥到LottieAnimationView的invalidateDrawable


<code class="language-js">@Override
public void invalidateDrawable(@NonNull Drawable dr) {
    if (getDrawable() == lottieDrawable) {
      // We always want to invalidate the root drawable so it redraws the whole drawable.
      // Eventually it would be great to be able to invalidate just the changed region.
        super.invalidateDrawable(lottieDrawable);
    } else {
      // Otherwise work as regular ImageView
        super.invalidateDrawable(dr);
    }
}

(5)最後觸發LottieDrawable重繪


<code class="language-js">@Override
public void draw(@NonNull Canvas canvas) {
    ...
    matrix.reset();
    matrix.preScale(scale, scale);
    compositionLayer.draw(canvas, matrix, alpha);   //這裡會呼叫所有layer的繪製方法
    if (hasExtraScale) {
        canvas.restore();
    }
}

五、效能

1.官方說明

如果沒有mask和mattes,那麼效能和記憶體非常好,沒有bitmap建立,大部分操作都是簡單的cavas繪製。

如果存在mattes,將會建立2~3個bitmap。bitmap在動畫載入到window時被建立,被window刪除時回收。所以不宜在RecyclerView中使用包涵mattes或者mask的動畫,否則會引起bitmap抖動。除了記憶體抖動,mattes和mask中必要的bitmap.eraseColor()和canvas.drawBitmap()也會降低動畫效能。對於簡單的動畫,在實際使用時效能不太明顯。

如果在列表中使用動畫,推薦使用快取LottieAnimationView.setAnimation(String, CacheStrategy) 。

2.屬性動畫和Lottie動畫對比

以下效能對比是以K歌內單個禮物動畫效果

屬性動畫 lottie使用硬體加速 lottie未使用硬體加速
幀率 img img img
內容 img img img
CPU img img img

Lottie動畫在未開啟硬體加速的情況下,幀率、記憶體,CPU都比屬性動畫差,開啟硬體加速後,效能差不多。

3、未開啟硬體加速,Lottie動畫大小幀率對比

0.12倍 1倍
img img

主要耗時在draw方法,繪製區域越小,耗時越小

六、K歌可用的場景

1.特性引導視訊

全民K歌每個大版本的首次啟動都會有視訊引導動畫,每次都會在清晰度和檔案大小平衡,最終匯出一個大概有3-4M的引導視訊,使用lottie可提高動畫清晰度和減小安裝包大小

2.loading動畫

img

img

3.禮物動畫

img

這是全民K歌的禮物面板,內部有大量禮物動畫,每個禮物動畫都不相同,動畫過程中有大量的旋轉,透明度,大小的變化,需要用屬性動畫實現,非常麻煩,程式碼可維護性也比較差。對比使用lottie後,有幾大優勢:

1、100%實現設計效果

2、客戶端程式碼量極少,易維護

3、每個動畫可動態配置動畫樣式(載入不同的json)

4、所有動畫都可動態配置,動畫配置檔案,素材都可從網上載入

4.說唱

img

K歌的說唱功能需要歌詞按照特定的動畫展示出來,這裡就涉及歌詞放大,縮小,旋轉等等特效。實現時,根據當前時間,在canvas上歌詞繪製出來,最終再和聲音融合在一起生成一個MV視訊,這裡就導致動畫不能特別複雜,並且有一定的規律。

如果使用lottie後,可以把效果匯出到json動畫檔案裡,客戶端載入動畫檔案,迴圈設定進度,讀取每幀畫面,再和聲音融合生成MV。

優勢:

1.動畫豐富

2.程式碼量少

3.可使用設計匯出的字型

程式碼


<code class="language-js">animationView.setProgress(progress);        //設定當前進度
animationView.buildDrawingCache();          //強制快取繪製資料
Bitmap image = animationView.getDrawingCache(); //獲取當前繪製資料

七、總結

1.劣勢

(1)效能不夠好—某些動畫特效,記憶體和效能不夠好;相對於屬性動畫,在展示大動畫時,幀率較低

2.優勢

(1)開發效率高—程式碼實現簡單,更換動畫方便,易於除錯和維護。

(2)資料來源多樣性—可從assets,sdcard,網路載入動畫資源,能做到不發版本,動態更新

(3)跨平臺—設計稿匯出一份動畫描述檔案,android,ios,react native通用

Lottie使用簡單,易於上手,非常值得嘗試。

八、參考資料

1.GitHub - airbnb/lottie-android: Render After Effects animations natively on Android and iOS

2.Lottie的使用及原理淺析 - 彩筆學長 - CSDN部落格

3.從json檔案到炫酷動畫-Lottie實現思路和原始碼分析 - 簡書

4.Most Popular - LottieFiles

此文已由作者授權騰訊雲+社群在各渠道釋出

獲取更多新鮮技術乾貨,可以關注我們騰訊雲技術社群-雲加社群官方號及知乎機構號