Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Vector 與 Animated-Vector 打造流暢的路徑描繪動畫

編輯:關於 Android 程式設計

自從 Google 在 v23.2 支援庫中把 AppCompat 全面改用 Vector 圖示後,AAR 包直接瘦身約 9%、將近 70KB,而這份好處會自動惠及所有相容版本。Vector 就是 SVG 在 Android 上的原生形式:自適應任何解析度、檔案極小,還能拿來做動畫。本文示範如何用它畫出一段會「自己長出來」的心形線。

先確認 SDK Manager 中的支援庫已更新到含 Vector 支援的版本。

整個動畫由三個部分組成:Vector 圖像本身、描述繪圖過程的路徑動畫,以及把兩者綁在一起的 Animated-Vector。

最終效果如下:

一、準備 Vector 圖像

把 SVG 轉成 Vector 資源,可以用 Android Studio 2.0 以上的 Vector Asset 精靈,也可以使用線上轉換工具。關鍵是圖形必須以 path 形式描述,才能被後續動畫控制。心形拆成左右兩半,各自命名為 heart1 與 heart2:

<vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:width="256dp"
    android:height="256dp"
    android:viewportHeight="70"
    android:viewportWidth="70">
    <path android:name="heart1" android:pathData="..." android:strokeColor="#E91E63" android:strokeWidth="1"/>
    <path android:name="heart2" android:pathData="..." android:strokeColor="#E91E63" android:strokeWidth="1"/>
</vector>

二、撰寫路徑動畫

路徑動畫其實就是一個普通的屬性動畫,重點在 trimPathEnd 這個屬性。它決定路徑被繪製的比例,取值 0 到 1,0 表示完全不畫、1 表示畫完:

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="6000"
    android:propertyName="trimPathEnd"
    android:valueFrom="0"
    android:valueTo="1"
    android:valueType="floatType"/>

duration 是毫秒數,這裡的 6000 代表六秒畫完,數值越小線條跑得越快。

三、用 Animated-Vector 把兩者接起來

這一步只是宣告:哪一個 path 要套用哪一段動畫。

<animated-vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:drawable="@drawable/v_heard">
    <target android:name="heart1" android:animation="@animator/heart_animator"/>
    <target android:name="heart2" android:animation="@animator/heart_animator"/>
    ...
</animated-vector>

四、啟動動畫

AnimatedVectorDrawable 需要 Android 5.0(API 21)以上,因此務必做版本判斷:

// 僅支援 5.0 以上版本
private void animateImage() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        AnimatedVectorDrawable mAnimatedVectorDrawable =
            (AnimatedVectorDrawable) ContextCompat.getDrawable(getApplication(), R.drawable.v_heard_animation);
        mIvImageView.setImageDrawable(mAnimatedVectorDrawable);
        if (mAnimatedVectorDrawable != null) {
            mAnimatedVectorDrawable.start();
        }
    }
}

start() 就是啟動的開關,呼叫後 trimPathEnd 會從 0 遞增到 1,線條便依序浮現。

為什麼值得用

同樣一段動畫, GIF 需要逐幀存成點陣圖,檔案動輒數百 KB 且無法任意縮放;Vector 動畫只是一份 XML 幾何描述,體積通常在 1KB 上下,任何解析度都清晰銳利,還能隨時改顏色、改速度。若需要更複雜的路徑變形,可以搭配官方支援庫的 AnimatedVectorDrawableCompat 做相容處理,也能參考社群開放的 SVG 資源庫找現成圖形。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved