我们矢量图除了可以不使用资源图片的情况下展示一个图标,还可以用来制作一些简单的动画效果。最主要的动画效果就是path路径变化形成的动画。这篇博客我们就学习一下如何做简单的矢量动画。
1.AnimatedVectorDrawable相关属性
- registerAnimationCallback:注册动画监听器,需实现Animation2.AnimationCallback接口的两个方法,即onAnimationStart和onAnimationEnd。
- start:开始播放动画。
- stop:停止播放。
- reverse:倒过来播放。
2.动画示例
首先我们要有一个矢量图文件
vector_face_eye.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="200dp"
android:width="200dp"
android:viewportHeight="100"
android:viewportWidth="100">
<!-- 下面定义了脸部轮廓的路径信息 -->
<path
android:fillColor="#ffff00"
android:pathData="M 50,50
m -48,0
a 48,48 0 1,0 96,0
a 48,48 0 1,0 -96,0" />
<!-- 下面定义了左眼的路径信息 -->
<path
android:name="eye_left"
android:strokeColor="@android:color/black"
android:strokeWidth="4"
android:strokeLineCap="round"
android:pathData="M 25,30
Q 35,40 45,30" />
<!-- 下面定义了右眼的路径信息 -->
<path
android:name="eye_right"
android:strokeColor="@android:color/black"
android:strokeWidth="4"
android:strokeLineCap="round"
android:pathData="M 55,30
Q 65,40 75,30" />
<!-- 下面定义了嘴巴的路径信息 -->
<path
android:name="mouth"
android:strokeColor="@android:color/black"
android:strokeWidth="4"
android:strokeLineCap="round"
android:pathData="M 30,75
Q 50,55 70,75" />
</vector>
接着是三个动画的定义文件,定义了两个眼睛和一个嘴巴的动画变换。我们可以把这个三个文件放到res > animator文件夹下。
anim_smile_eye_left.xml
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:propertyName="pathData"
android:valueFrom="M 25,30
Q 35,40 45,30"
android:valueTo="M 25,40
Q 35,30 45,40"
android:valueType="pathType"
android:interpolator="@android:anim/accelerate_interpolator" />
anim_smile_eye_right.xml
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:propertyName="pathData"
android:valueFrom="M 55,30
Q 65,40 75,30"
android:valueTo="M 55,40
Q 65,30 75,40"
android:valueType="pathType"
android:interpolator="@android:anim/accelerate_interpolator" />
anim_smile_mouth.xml
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
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"
android:interpolator="@android:anim/accelerate_interpolator" />
接着我们要把这三个动画连接并指向对应部位
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/vector_face_eye">
<target
android:name="mouth"
android:animation="@animator/anim_smile_mouth" />
<target
android:name="eye_left"
android:animation="@animator/anim_smile_eye_left" />
<target
android:name="eye_right"
android:animation="@animator/anim_smile_eye_right" />
</animated-vector>
开启动画
iv_vector.setImageResource(R.drawable.animated_vector_smile_eye);
((Animatable)iv_vector.getDrawable()).start();