算是比较元老级的一个功能了(简单说没啥用),如有说错欢迎指正
正好最近看到创建项目时就自带的ic_launcher_background.xml这个图标感到疑惑,看到相关资料都是百度云下载链接,干脆直接学习了一下写个手记
操作效果与自定义view基本一样,先说一下如何使用:
- moveto 命令 M 移动到新的位置,即path.moveTo(x,y)
- closepath 命令 Z 封闭路径,闭合到起始位置,即path.close()
- lineto 命令 L ,画一条线到指定的位置,即path.lineTo(x,y)
- horizontal lineto 命令 H 水平画一条直线到指定位置,即竖着画线到一个X值
- vertical lineto 命令 V 垂直画一条直线到指定位置,即横着画线到一个Y指
- 贝塞尔曲线 命令 Q,即path.quadTo(x1,y1,x2,y2)
- 还有2个 目前不知道咋用,一个是二阶贝塞尔的 T,另一个是椭圆的 A,以后补充吧
android:pathData的每个值需要用空格隔开,看起始图和代码说话,my_path.xml放drawable下
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="50dp"
android:height="50dp"
android:viewportWidth="50.0"
android:viewportHeight="50.0">
<path
android:name="testpath"
android:pathData="M10,10 L20,30 V10 H30 Q40,10,30,30 "
android:strokeWidth="5"
android:strokeColor="#F2AC"
android:strokeLineCap="round"
android:strokeLineJoin="round"
/>
<!-- android:pathData="M15,20 Q30,20,20,30 M20,30 Q30,40,15,40"-->
</vector>
接下来是图形变换了
创建my_anim.xml在drawable下,animated-vector应该会爆红让你在drawble-v21也创建个文件
<?xml version="1.0" encoding="utf-8"?>
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/my_path">
<target
android:animation="@animator/my_animator"
android:name="testpath"/>
</animated-vector>
接下来在res创建个animtor文件夹,并创建文件my_animator.xml
android:valueFrom与android:valueTo的值必须一一对应,不然会闪退,不信的话可以试一下
<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:interpolator/decelerate_cubic"
android:duration="5000"
android:repeatMode="reverse"
android:repeatCount="infinite"
android:propertyName="pathData"
android:valueFrom="M10,10 L20,30 V10 H30 Q40,10,30,30"
android:valueTo="M20,25 L10,25 V35 H20 Q20,0,30,30"
android:valueType="pathType">
<!-- android:valueFrom="M15,20 Q30,20,20,30 M20,30 Q30,40,15,40"
android:valueTo="M15,10 Q10,40,25,40 M25,40 Q40,25,15,30" -->
</objectAnimator>
在Activity中加入以下代码:
ImageView mIcAnim = findViewById(R.id.ic_test);
AnimatedVectorDrawable drawable = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
drawable = (AnimatedVectorDrawable) getDrawable(R.drawable.my_anim);
mIcAnim.setImageDrawable(drawable);
}
if (drawable != null) {
drawable.start();
}
在draw的布局文件加入
<ImageView
android:id="@+id/ic_test"
android:layout_width="wrap_content"
android:src="@drawable/my_path"
android:layout_height="wrap_content" />
如下是变化后的图片:
到此完成了,即可以看到这个imageview的完整变化了,可以拿代码去玩玩,如果学会了的话my_path.xml和my_animator.xml下的注释替换掉原来的位置运行一下
转载请注明出处