创建一个简单的SVG动画实例
主要用到以下三部分:
- VectorDrawable
- AnimatedVectorDrawable
- objectAnimator
1. 创建静态的SVG图形
在res/drawable文件夹下line.xml
对应的vector即为静态的VectorDrawable。
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="200dp"
android:height="200dp"
android:viewportHeight="100"
android:viewportWidth="100">
<group>
<path
android:name="path1"
android:pathData="
M 20 80
L 50,80 80,80"
android:strokeColor="@android:color/holo_blue_light"
android:strokeLineCap="round"
android:strokeWidth="5" />
<path
android:name="path2"
android:pathData="
M 20,20
L 50,20 80,20"
android:strokeColor="@android:color/holo_blue_light"
android:strokeLineCap="round"
android:strokeWidth="5" />
</group>
</vector>
涉及到的相关属性:
android:width
以及android:height
代表具体大小android:viewportHeight
以及android:viewportWidth
表示SVG图形的划分比例。比如上边的代码,将200dp划分为100份,如何过在绘制图形的过程中使用坐标(50,50),则意味着改坐标位与该SVG图形的正中间。因此,height、width的比例与viewHeight、viewWidth的比例必须保持一致,不然图形就会发生压缩、变形。—出自徐宜生《Android群英传》
android:strokeColor
绘制的为非填充的图形android:fillColor
绘制的为填充图形android:strokeLineCap="round"
用来设置直线两端为圆形。
2. 在XML中实现objectAnimator动画
在res/animator文件夹下新建path1、path2两个xml文件
path1.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:interpolator="@android:anim/linear_interpolator"
android:propertyName="pathData"
android:valueFrom="M 20,80 L 50,80 80,80"
android:valueTo="M 20,80 L 50,50 80,80"
android:valueType="pathType">
</objectAnimator>
path2.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:interpolator="@android:anim/linear_interpolator"
android:propertyName="pathData"
android:valueFrom="M 20,20 L 50,20 80,20"
android:valueTo="M 20,20 L 50,50 80,20"
android:valueType="pathType">
</objectAnimator>
两块代码基本一致,实现的是上下两条直线同时从中点想两条直线中间折起从而达成从“=”向“×”的变换效果。
3. 使用AnimatedVectorDrawable将VectorDrawable与objectAnimator“黏合”在一起
在res/drawable文件夹下新建vector.xml文件
<?xml version="1.0" encoding="utf-8"?>
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/line">
<target
android:name="path1"
android:animation="@animator/path1">
</target>
<target
android:animation="@animator/path2"
android:name="path2">
</target>
</animated-vector>
注意<target>
标签下的name
要与line.xml文件中<path>
的name
保持一致。
4. 在代码中启动动画
public class MainActivity extends AppCompatActivity {
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
animate();
}
});
}
private void animate() {
Drawable drawable = iv.getDrawable();
if (drawable instanceof Animatable) {
((Animatable)drawable).start();
}
}
以上实现了一个简单的SVG动画实例。