Android VectorDrawable SVG 動畫

趙子龍發表於2017-11-12

Android 5.0系統中引入了 VectorDrawable 來支援向量圖(SVG),同時還引入了 AnimatedVectorDrawable 來支援向量圖動畫

1 建立svg靜態圖形(VectorDrawable)

res/drawable/rectangle.xml

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="400dp"
    android:height="400dp"
    android:viewportHeight="400"
    android:viewportWidth="400">

    <path
        android:name="rect_vector"
        android:fillColor="#04f91d"
        android:pathData="M 100 100 L 300 100 L 300 300 L 100 300 z"
        android:strokeColor="#f76f07"
        android:strokeWidth="5" />

</vector>複製程式碼

在這裡建立的是一個矩形

2 建立屬性動畫

res/animator/changecolor.xml

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:propertyName="fillColor"
    android:duration="5000"
    android:valueFrom="@android:color/black"
    android:valueTo="@android:color/holo_green_light"
    android:valueType="colorType">
</objectAnimator>複製程式碼

propertyName 定義為fillColor,也就是動態的改變圖形的填充顏色
duration 定義執行時間為 5000 毫秒
valueFrom 定義開始的顏色
valueTo 定義為將要過渡到的顏色
valueType 定義改變的屬性的型別

3 使用animated-vector連線vectordrawable和屬性動畫,命名為change_color.xml

<?xml version="1.0" encoding="utf-8"?>
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:drawable="@drawable/rectangle"
    tools:targetApi="lollipop">

    <target
        android:animation="@animator/changecolor"
        android:name="rect_vector"/>

</animated-vector>複製程式碼

animated-vector 節點下 drawable定義載入 靜態VectorDrawable圖形
target 節點用來關聯屬性動畫與 靜態VectorDrawable圖形
target 節點下 animation定義載入將要執行的動畫檔案
target 節點下 name 定義對應的屬性動畫將要執行在 哪個路徑上

4 程式碼中載入使用


private AnimatedVectorDrawable mDrawable;
//獲取AnimatedVectorDrawable
mDrawable = (AnimatedVectorDrawable) getResources().getDrawable(R.drawable.change_color);
//關聯imageView
imageView.setImageDrawable(mDrawable);
//開啟動畫
mDrawable.start();複製程式碼

相關文章