Android VectorDrawable SVG 動畫

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

1 建立svg靜態圖形(VectorDrawable)

res/drawable/rectangle.xmlbash

<?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>複製代碼

在這裏建立的是一個矩形svg

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 定義改變的屬性的類型spa

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 定義對應的屬性動畫將要執行在 哪一個路徑上code

4 代碼中加載使用

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

相關文章
相關標籤/搜索