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

Android VectorDrawable 與 SVG:動手做兩個炫酷的向量動畫

編輯:關於 Android 程式設計

Android 從 5.0 開始提供了新的 API VectorDrawable,讓我們可以直接使用向量圖 SVG。在 XML 檔中,透過 <vector>、<group>、<path> 這幾個關鍵節點,就能完成 SVG 圖形的描述以及動畫的實作。

下面用兩個實例,完整走一遍 VectorDrawable 與 SVG 動畫的用法。

登錄特效

搜索特效

一、登錄特效的實作

先把動畫拆開來看。整個特效對應的 SVG 圖案如下:

圖案由五個部分組成:兩條橫線、兩個半圓,以及一個對號。為了方便標示,這裡把顏色稍微改過。

1. 用 vector 標籤畫出圖形

edit_login.xml(放在 res/drawable 目錄下):

<vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:width="300dp"
    android:height="96dp"
    android:viewportWidth="150"
    android:viewportHeight="48">

    <!-- 第一條橫線 -->
    <path
        android:name="bar"
        android:pathData="M0,23 L140,23"
        android:strokeAlpha="0.8"
        android:strokeColor="@color/colorAccent"
        android:strokeLineCap="square"
        android:strokeWidth="1" />

    <!-- 向上的圓弧 -->
    <path
        android:name="round"
        android:pathData="M138 23 A 10 10 0 1 0 128 13"
        android:strokeAlpha="0.8"
        android:strokeColor="@color/colorAccent"
        android:strokeLineCap="round"
        android:strokeWidth="1" />

    <!-- 對號 -->
    <path
        android:name="right"
        android:pathData="M128 13 l 3 3 l 5 -6"
        android:strokeAlpha="0.8"
        android:strokeColor="@color/colorAccent"
        android:strokeLineCap="round"
        android:strokeWidth="1" />

    <!-- 向下的圓弧 -->
    <path
        android:name="round2"
        android:pathData="M138 23 A 10 10 0 1 1 138 43"
        android:strokeAlpha="0.8"
        android:strokeColor="@color/colorAccent"
        android:strokeLineCap="round"
        android:strokeWidth="1" />

    <!-- 第二條橫線 -->
    <path
        android:name="bar2"
        android:pathData="M140,43 L0,43"
        android:strokeAlpha="0.8"
        android:strokeColor="@color/colorAccent"
        android:strokeLineCap="square"
        android:strokeWidth="1" />
</vector>

寫好之後,Android Studio 的預覽視窗可以直接看到圖形,不用跑模擬器。

2. 兩個核心標籤

<vector>:定義整個畫布。

width:畫布寬度。
height:畫布高度。
viewportWidth:把實際寬度劃分成多少個相對單元(這裡 300dp 被切成 150 個單元)。
viewportHeight:把實際高度劃分成多少個相對單元(96dp 切成 48 個單元)。

viewport 的意義在於:無論實際顯示尺寸是多少,路徑座標都在同一套虛擬座標系裡描述,這正是向量圖能任意縮放不失真、也天生適配各種螢幕的原因。

<path>:畫出具體圖形,相當於畫筆。

name:宣告一個標記,類似 id,做動畫時靠它找到節點。
pathData:SVG 路徑描述。
strokeWidth:畫筆寬度。
strokeColor:畫筆顏色。
strokeAlpha:透明度。
strokeLineCap:線條端點的形狀,可為平頭或圓角。

3. 拆解動畫階段

圖畫好之後,整個動畫可以分成幾個階段:

初次點擊第一個輸入框:1 動畫顯示,2、3、4、5 不顯示。
驗證輸入是否正確,若正確:1 保持顯示,2、3 動畫顯示,4、5 隱藏。
點擊第二個輸入框,第一條橫線過渡到第二條橫線:1 動畫隱藏,2 隱藏,3 顯示,4、5 動畫顯示。

其餘的用戶交互細節這裡不展開。

4. 定義三段動畫

依上面的順序,分別建立 anim1.xml、anim2.xml、anim3.xml(放在 drawable 目錄中,命名請自行斟酌)。

anim1.xml

<animated-vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:drawable="@drawable/edit_login">

    <target
        android:name="bar"
        android:animation="@animator/anim_bar_fill" />
    <target
        android:name="round"
        android:animation="@animator/anim_default_gone" />
    <target
        android:name="right"
        android:animation="@animator/anim_default_gone" />
    <target
        android:name="round2"
        android:animation="@animator/anim_default_gone" />
    <target
        android:name="bar2"
        android:animation="@animator/anim_default_gone" />
</animated-vector>

anim2.xml

<animated-vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:drawable="@drawable/edit_login">

    <target
        android:name="bar"
        android:animation="@animator/anim_default" />
    <target
        android:name="round"
        android:animation="@animator/anim_round" />
    <target
        android:name="right"
        android:animation="@animator/anim_aa" />
    <target
        android:name="round2"
        android:animation="@animator/anim_default_gone" />
    <target
        android:name="bar2"
        android:animation="@animator/anim_default_gone" />
</animated-vector>

anim3.xml

<animated-vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:drawable="@drawable/edit_login">

    <target
        android:name="bar"
        android:animation="@animator/anim_bar_empty" />
    <target
        android:name="round"
        android:animation="@animator/anim_default_gone" />
    <target
        android:name="right"
        android:animation="@animator/anim_default" />
    <target
        android:name="round2"
        android:animation="@animator/anim_round2" />
    <target
        android:name="bar2"
        android:animation="@animator/anim_bar_fill2" />
</animated-vector>

這三個檔案最外層都用 <animated-vector> 包裹,它的作用像一座橋,把靜態的 SVG 與各段動畫整合成一個新的 Drawable。

drawable:目標 SVG。
<target>:為 SVG 中的每一個 <path> 指定不同的動畫。
name:目標節點的標識(對應 path 的 name)。
animation:該節點要播放的動畫。

5. 屬性動畫檔(放在 animator 目錄)

這裡定義了很多個動畫,其中「預設顯示」與「預設隱藏」這兩個是沒有動畫效果的,只是用來固定初始狀態。因為都是屬性動畫,所以必須放在 animator 資料夾而不是 anim。

anim_default.xml(預設顯示)

<objectAnimator xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="0"
    android:propertyName="trimPathEnd"
    android:valueFrom="1"
    android:valueTo="1"
    android:valueType="floatType" />

anim_default_gone.xml(預設隱藏)

<objectAnimator xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="0"
    android:propertyName="trimPathEnd"
    android:valueFrom="0"
    android:valueTo="0"
    android:valueType="floatType" />

anim_bar_fill.xml(橫線 1 的顯示動畫)

<objectAnimator xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="500"
    android:propertyName="trimPathEnd"
    android:valueFrom="0"
    android:valueTo="1"
    android:valueType="floatType" />

anim_bar_empty.xml(橫線 1 的隱藏動畫)

<objectAnimator xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="500"
    android:propertyName="trimPathEnd"
    android:valueFrom="1"
    android:valueTo="0"
    android:valueType="floatType" />

其餘的 anim_round.xml(圓弧 2 顯示)、anim_aa.xml(對號 3 顯示)、anim_round2.xml(圓弧 4 顯示)、anim_bar_fill2.xml(橫線 5 顯示)寫法完全相同,只是 duration 與 valueFrom / valueTo 略有差異,用來製造先後遲滯的錯落感。

這裡出現了一個前面沒提過的屬性:trimPathEnd。它也是 <path> 的屬性,決定該節點所畫出的線條顯示的百分比,範圍 0~1,代表從起點到終點顯示的比例。與它成對的還有 trimPathStart,代表隱藏的百分比,0~1 表示從起點開始隱藏的比例。兩者搭配,就能做出「線條自己長出來」的效果。

6. 佈局檔

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <!-- 用來顯示 SVG 圖案與動畫 -->
        <ImageView
            android:id="@+id/img1"
            android:layout_width="300dp"
            android:layout_height="96dp"
            android:layout_gravity="center"
            android:focusable="true"
            android:focusableInTouchMode="true">

            <EditText
                android:id="@+id/edit1"
                android:layout_width="300dp"
                android:layout_height="45dp"
                android:layout_gravity="center"
                android:background="@null"
                android:hint="Email"
                android:paddingStart="4dp"
                android:textColor="?android:colorAccent"
                android:textColorHint="@color/colorPrimary"
                android:textSize="12sp" />

            <EditText
                android:id="@+id/edit2"
                android:layout_width="300dp"
                android:layout_height="45dp"
                android:layout_below="@+id/edit1"
                android:layout_gravity="center"
                android:background="@null"
                android:hint="Email"
                android:paddingStart="4dp"
                android:textColor="?android:colorAccent"
                android:textColorHint="@color/colorPrimary"
                android:textSize="12sp" />
        </ImageView>
    </RelativeLayout>
</LinearLayout>

兩個輸入框之間要留出間隔,用來呈現動畫。另外因為存在輸入框,打開頁面時會自動彈出軟鍵盤,所以把焦點刻意放在 ImageView 上(focusableInTouchMode="true")來避免這個問題。

7. Activity 中的使用

/**
 * SVG 動畫
 */
public class SVGMainActivity extends AppCompatActivity
        implements View.OnFocusChangeListener, TextWatcher {

    private ImageView img1;
    private EditText edit1, edit2;

    private AnimatedVectorDrawable anim1, anim2, anim3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_svg);

        img1 = (ImageView) findViewById(R.id.img1);
        edit1 = (EditText) findViewById(R.id.edit1);
        edit2 = (EditText) findViewById(R.id.edit2);

        // 載入 SVG 動畫
        anim1 = (AnimatedVectorDrawable) getResources().getDrawable(R.drawable.anim1);
        anim2 = (AnimatedVectorDrawable) getResources().getDrawable(R.drawable.anim2);
        anim3 = (AnimatedVectorDrawable) getResources().getDrawable(R.drawable.anim3);

        // 焦點變化監聽
        edit1.setOnFocusChangeListener(this);
        edit2.setOnFocusChangeListener(this);

        // 文本變化監聽
        edit1.addTextChangedListener(this);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.edit1:
                if (hasFocus) {
                    img1.setImageDrawable(anim1);
                    anim1.start();
                }
                break;
            case R.id.edit2:
                if (hasFocus) {
                    img1.setImageDrawable(anim3);
                    anim3.start();
                }
                break;
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        // 內容變化後判斷是否正確
        if (!TextUtils.isEmpty(s) && edit1.getText().toString().trim().equals("1234")) {
            Toast.makeText(SVGMainActivity.this, "right", Toast.LENGTH_SHORT).show();
            img1.setImageDrawable(anim2);
            anim2.start();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}
}

核心只有三個步驟:

1. (AnimatedVectorDrawable) getResources().getDrawable(R.drawable.anim1) —— 把 XML 載入成 Drawable 並轉型為 AnimatedVectorDrawable。
2. img1.setImageDrawable(anim1) —— 設定 Drawable。
3. anim1.start() —— 啟動動畫。

細節處理上還有很多可以打磨的地方,這裡只做了一個最簡單的示範。

二、SVG Path Data 語法速查

上面定義圖形時,<path> 的 pathData 用字元與數字描述出了一整個圖案。主要命令有:

M:move to,移動繪製點
L:line to,直線
Z:close,閉合
C:cubic bezier,三次貝賽爾曲線
Q:quadratic bezier,二次貝賽爾曲線
A:arc,圓弧

每個命令都有大寫與小寫兩種寫法:大寫代表絕對座標,小寫代表相對於當前點的相對座標。

實務上唯一需要特別說明的是圓弧 A。以 M138 23 A 10 10 0 1 0 128 13 為例:

M138 23:先把畫筆移動到 (138, 23)。
A 10 10 0 1 0 128 13:畫圓弧,七個參數依序為 x 軸半徑、y 軸半徑、x 軸旋轉偏移量、大/小弧度(0 取小弧度,1 取大弧度)、方向(0 逆時針,1 順時針)、目標 X 座標、目標 Y 座標。

三、搜索特效的實作

依前面同樣的四個步驟進行:定義 SVG 圖形 → 建立 VectorDrawable XML → 定義動畫 → 載入使用。

search_bar.xml(畫出 SVG)

<vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:width="150dp"
    android:height="24dp"
    android:viewportWidth="150"
    android:viewportHeight="24">

    <!-- 搜索圖案 -->
    <path
        android:name="search"
        android:pathData="M141,17 A9,9 0 1,1 142,16 L149,23"
        android:strokeAlpha="0.8"
        android:strokeColor="#ffffff"
        android:strokeLineCap="round"
        android:strokeWidth="2" />

    <!-- 下劃線 -->
    <path
        android:name="bar"
        android:pathData="M0,23 L149,23"
        android:strokeAlpha="0.8"
        android:strokeColor="#ffffff"
        android:strokeLineCap="square"
        android:strokeWidth="2" />
</vector>

anim_bar_to_search.xml(下劃線過渡成搜索圖案)

<animated-vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:drawable="@drawable/search_bar">

    <target
        android:name="search"
        android:animation="@animator/anim_search_fill" />
    <target
        android:name="bar"
        android:animation="@animator/anim_bar_empty" />
</animated-vector>

anim_search_to_bar.xml(搜索圖案退回下劃線)

<animated-vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:drawable="@drawable/search_bar">

    <target
        android:name="search"
        android:animation="@animator/anim_search_empty" />
    <target
        android:name="bar"
        android:animation="@animator/anim_bar_fill" />
</animated-vector>

其中下劃線的顯示與隱藏動畫直接沿用上一個例子;搜索圖案的顯示/隱藏(anim_search_fill、anim_search_empty)寫法也一樣,只是操作的路徑換成放大鏡那一段。

佈局面

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:colorPrimary"
    android:gravity="center"
    android:onClick="lost_focus">

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:focusableInTouchMode="true">

        <ImageView
            android:id="@+id/search"
            android:layout_width="150dp"
            android:layout_height="24dp"
            android:onClick="animate"
            android:src="@drawable/search_bar">

            <EditText
                android:id="@+id/text"
                android:layout_width="121dp"
                android:layout_height="22dp"
                android:alpha="0"
                android:background="@null"
                android:paddingStart="4dp"
                android:textColor="?android:colorAccent"
                android:textSize="12sp" />
        </ImageView>
    </FrameLayout>
</LinearLayout>

最外層掛了點擊事件:點擊輸入框以外的區域時顯示放大鏡圖示,點擊圖示時顯示下劃線,同時把焦點從輸入框移開。

Activity

/**
 * 搜索動畫的實作
 */
public class SVGMain2Activity extends AppCompatActivity {

    private ImageView iv;
    private TextView text;
    private AnimatedVectorDrawable searchToBar;
    private AnimatedVectorDrawable barToSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_svg2);

        iv = (ImageView) findViewById(R.id.search);
        text = (TextView) findViewById(R.id.text);

        // 載入 SVG 動畫
        searchToBar = (AnimatedVectorDrawable) getResources()
                .getDrawable(R.drawable.anim_search_to_bar);
        barToSearch = (AnimatedVectorDrawable) getResources()
                .getDrawable(R.drawable.anim_bar_to_search);

        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv.setImageDrawable(searchToBar);
                searchToBar.start();
            }
        });
    }

    /** 點擊輸入框之外時,隱藏下劃線 */
    public void lost_focus(View view) {
        iv.setImageDrawable(barToSearch);
        barToSearch.start();
    }
}

四、結語

VectorDrawable 的價值不只是「省掉好幾套 PNG」,更在於它把圖形變成了可被程式操控的資料——透過 trimPathEnd 這類屬性,線條的生長、收縮、變形都能用屬性動畫平滑驅動。缺點是複雜圖形的 pathData 手寫成本很高,實務上通常交給設計工具(如 Android Studio 的 SVG 轉換或 Illustrator 匯出)產生,工程師再專注在動畫節奏的調校上。

另外要注意相容性:VectorDrawable 原生支援 API 21 以上,若需向下相容,記得在 gradle 中啟用 vectorDrawables.useSupportLibrary 並改用 AppCompat 的元件。

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