AnimatedVectorDrawable类可以去创建一个矢量资源的动画
先看效果图
Animated Vector Drawables实现动画主要分三个步骤:
- 1.画出SVG图片
- 2.画出动画变化路径/条件
- 3.通过animated-vector将图片和动画连接起来
vector_smile.xml
"1.0" encoding="utf-8"?>
"http://schemas.android.com/apk/res/android"
android:width="200dp"
android:height="200dp"
android:viewportHeight="100"
android:viewportWidth="100">
"@color/yello"
android:pathData="M 50,50 m -48 ,0 a 48,48 0 1,0 96,0 a 48,48 0 1,0 -96,0"/>
"eye_left"
android:pathData="M 28,40 Q 36,50 43,40"
android:strokeColor="@color/colorBlack"
android:strokeLineCap="round"
android:strokeWidth="4"/>
"eye_right"
android:pathData="M 58,40 Q 66,50 73,40"
android:strokeColor="@color/colorBlack"
android:strokeLineCap="round"
android:strokeWidth="4"/>
"smile"
android:pathData="M 30,75 Q 50,55 70,75"
android:strokeColor="@color/colorBlack"
android:strokeLineCap="round"
android:strokeWidth="4"/>
OK,一个笑脸的SVG图片就画好了,如果还不熟悉如何画SVG图片,请看这篇博客学习SVG 矢量图
我们需要为每个变化的部分添加动画:
animator_eye_left.xml
"1.0" encoding="utf-8"?>
"http://schemas.android.com/apk/res/android"
android:duration="1000"
android:interpolator="@android:anim/accelerate_interpolator"
android:propertyName="pathData"
android:valueFrom="M 28,40 Q 36,50 43,40"
android:valueTo="M 28,40 Q 36,30 43,40"
android:valueType="pathType"/>
animator_eye_right.xml
"1.0" encoding="utf-8"?>
"http://schemas.android.com/apk/res/android"
android:duration="1000"
android:interpolator="@android:anim/accelerate_interpolator"
android:propertyName="pathData"
android:valueFrom="M 58,40 Q 66,50 73,40"
android:valueTo="M 58,40 Q 66,30 73,40"
android:valueType="pathType"/>
animator_mouth_smile.xml
"1.0" encoding="utf-8"?>
"http://schemas.android.com/apk/res/android"
android:duration="1000"
android:interpolator="@android:anim/accelerate_interpolator"
android:propertyName="pathData"
android:valueFrom="M 30,75 Q 50,55 70,75"
android:valueTo="M 30,65 Q 50,85 70,65"
android:valueType="pathType"/>
propertyName指定控制的属性
valueFrom和valueTo控制动画的起始值
类似的情况:
animated_smile.xml
"1.0" encoding="utf-8"?>
"http://schemas.android.com/apk/res/android"
android:drawable="@drawable/vector_smile">
"eye_left"
android:animation="@animator/animator_eye_left"/>
"eye_right"
android:animation="@animator/animator_eye_right"/>
"smile"
android:animation="@animator/animator_mouth_smile"/>
先将AnimatedVectorDrawable XML 文件(animated_smile.xml)给一个ImageView设置背景
"@+id/image_smile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/animated_smile"/>
在代码中 ((Animatable) imageView.getDrawable()).start();