前端動畫交互

一、簡介

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 文件添加依賴

dependencies {  
  compile 'com.airbnb.android:lottie:2.1.0'
}

2.添加 Adobe After Effects 導出的動畫文件

Lottie默認讀取Assets中的文件,我們需要把動畫文件react.json 保存在app/src/main/assets文件裏。(文件比較大,只展示了部分內容,文件鏈接

{
    "v": "4.6.0", 
    "fr": 29.9700012207031, 
    "ip": 0, 
    "op": 141.000005743048, 
    "w": 800, 
    "h": 800, 
    "ddd": 0, 
    "assets": [ ], 
    "layers": [
        {
            "ddd": 0, 
            "ind": 0, 
            "ty": 4, 
            "nm": "center_circle", 
            "ks": {...}, 
            "ao": 0, 
            "shapes": [...], 
            "ip": 0, 
            "op": 900.000036657751, 
            "st": 0, 
            "bm": 0, 
            "sr": 1
        }, 
        {...}, 
        {...}, 
        {...}
    ]
}

3.使用Lottie

在佈局文件中直接添加Lottie的LottieAnimationView控件,即可在界面顯示React logo動畫效果

<com.airbnb.lottie.LottieAnimationView
        android:id="@+id/animation_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:lottie_fileName="react.json"
        app:lottie_loop="true"
        app:lottie_autoPlay="true" />

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動畫文件

StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(JSON_PATH + "react.json")));
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圖片

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, "", e);
        }
        return null;
    }
});

3.加載SDCard字體

animationView.setFontAssetDelegate(new FontAssetDelegate(){
    public Typeface fetchFont(String fontFamily) {
        Typeface customFont = Typeface.createFromFile(FONT_PATH + fontFamily);
        return customFont;
    }
});

4.緩存動畫

/*
* 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動畫描述文件:

{
    "v": "4.6.0", 
    "fr": 29.9700012207031, 
    "ip": 0, 
    "op": 141.000005743048, 
    "w": 800, 
    "h": 800, 
    "ddd": 0, 
    "assets": [ ], 
    "layers": [
        {...}, 
    ]
}

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外部結構

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

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

      long startFrame = json.optLong("ip", 0);
      long endFrame = json.optLong("op", 0);
      float frameRate = (float) json.optDouble("fr", 0);
      String version = json.optString("v");
      String[] versions = version.split("[.]");
      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("assets");
      parseImages(assetsJson, composition); //解析圖片
      parsePrecomps(assetsJson, composition);
      parseFonts(json.optJSONObject("fonts"), composition); //解析字體
      parseChars(json.optJSONArray("chars"), composition);  //解析字符
      parseLayers(json, composition);   //解析圖層
      return composition;
    }

(2)解析圖片資源

LottieImageAsset類封裝圖片信息

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

(3)解析圖層

Layer封裝圖層信息,現在lottie只支持PreComp,Solid,Image,Null,Shape,Text這6中圖層。

"layers": [                 //圖層信息
    {                       //第一層動畫
        "ddd": 0, 
        "ind": 0,           //layer id 圖層 id
        "ty": 4,            //圖層類型
        "nm": "center_circle", 
        "ks": {...},        //動畫
        "ao": 0, 
        "shapes": [...], 
        "ip": 0,            //inFrame 該圖層起始關鍵幀
        "op": 90,           //outFrame 該圖層結束關鍵幀
        "st": 0,            //startFrame 開始
        "bm": 0, 
        "sr": 1
    }, 
    {...}                   //第n層動畫
]

2.如何動起來

Lottie時序圖:

img

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

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

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

代碼如下:

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把進度傳遞到各個圖層

@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 >= 0; i--) {
        layers.get(i).setProgress(progress);
    }
}

(3)通知進度改變

  void setProgress(@FloatRange(from = 0f, to = 1f) float progress) {
    if (progress < getStartDelayProgress()) {
      progress = 0f;
    } else if (progress > getEndProgress()) {
      progress = 1f;
    }

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

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

(4)最終回調到LottieAnimationView的invalidateDrawable

@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重繪

@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.可使用設計導出的字體

代碼

animationView.setProgress(progress);        //設置當前進度
animationView.buildDrawingCache();          //強制緩存繪製數據
Bitmap image = animationView.getDrawingCache(); //獲取當前繪製數據

七、總結

1.劣勢

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

2.優勢

(1)開發效率高—代碼實現簡單,更換動畫方便,易於調試和維護。

(2)數據源多樣性—可從assets,sdcard,網絡加載動畫資源,能做到不發版本,動態更新

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

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章