轉載自:http://blog.csdn.net/ljx19900116/article/details/41806875
前言
示例代碼地址:animated-vector-drawable
幾句代碼,幾個配置文件即可實現以上效果,流暢的體驗,無縫的動畫,贊~!
官方文檔:點擊傳送
VectorDrawable
AnimatedVectorDrawable
AnimatedVectorDrawable類可以去創建一個矢量資源的動畫。
你通常在三個XML文件中定義矢量資源的動畫載體:
<vector>元素的矢量資源,在res/drawable/(文件夾)
<animated-vector>元素的矢量資源動畫,在res/drawable/(文件夾)
< objectAnimator>元素的一個或多個對象動畫器,在res/anim/(文件夾)
矢量資源動畫能創建<group>和<path>元素屬性的動畫。<group>元素定義了一組路徑或子組,並且<path>元素定義了要被繪製的路徑。
當你想要創建動畫時去定義矢量資源,使用Android:name屬性分配一個唯一的名字給組和路徑,這樣你可以從你的動畫定義中查詢到它們。
接下來我就以旋轉的小三角爲例:
看之前我們要思考一個問題,它是如何做到在邊旋轉的過程中變化形狀的。
首先我們先看一下小三角的vector文件:
- <animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:drawable="@drawable/vectordrawable" >
- <target
- android:name="rotationGroup"
- android:animation="@anim/rotation" />
- <target
- android:name="v"
- android:animation="@anim/path_morph" />
- </animated-vector>
旋轉動畫:
- <objectAnimator
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:duration="6000"
- android:propertyName="rotation"
- android:valueFrom="0"
- android:valueTo="360"/>
- <objectAnimator
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:duration="3000"
- android:propertyName="pathData"
- android:valueFrom="M300,70 l 0,-70 70,70 0,0 -70,70z"
- android:valueTo="M300,70 l 0,-70 70,0 0,140 -70,0 z"
- android:valueType="pathType"/>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/container"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- android:gravity="center_horizontal"
- android:orientation="vertical"
- tools:context=".ExampleActivity">
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="@dimen/margin"
- android:text="@string/example_from_documentation"
- android:drawableBottom="@drawable/avd"/>
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="@dimen/margin"
- android:text="@string/rotation_only"
- android:drawableBottom="@drawable/avd_rotation_only"/>
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="@dimen/margin"
- android:text="@string/path_morph_only"
- android:drawableBottom="@drawable/avd_path_morph_only"/>
- </LinearLayout>
配置了一個avb也就是上面貼的animated-vector文件。
- TextView textView = (TextView) view;
- for (final Drawable drawable : textView.getCompoundDrawables()) {
- if (drawable instanceof Animatable) {
- ((Animatable) drawable).start();
- }
- }