在之前一篇文章中利用drawLine实现了线条动画的效果,然后在大佬的介绍下查看了TrimPathStart/End,感觉有必要写一篇文章。
以下是本篇文章正文内容
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="200dp"
android:height="200dp"
android:viewportWidth="200"
android:viewportHeight="200">
<path
android:name="start"
android:pathData="M100 4 l-100 192 l192 0 z"
android:strokeWidth="3"
android:strokeColor="#a2d7dc"/>
</vector>
看看大致的动画效果(动画执行效果,顺序与绘制相反)
参数定义:大写的命令为绝对坐标命令;小写的命令为相对坐标命令
代码如下:
android:pathData="M100 4 l-100 192 l192 0 z"
//为了方便讲解改成如下
android:pathData="M100 4 l-100 192 l192 0 l-92,-194"
M100 4:起点为100,4(x为100,y为4)。 l-100 192: l命令是从当前的位置画一条线到指定位置,-100是减少 ,从最开始的值开始计算100-100,4+192,第二个点为0,196(x为0,y为196)。 l192 0 :同上,从上一个点计算0+192,196+0,第三个点为 192,196(x为192,y为196)。 l-92,-194:回到原点。
实际绘制效果:
defaultConfig {
...........
//增加对vectorDrawables的支持
vectorDrawables.useSupportLibrary = true
}
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="200dp"
android:height="200dp"
android:viewportWidth="200"
android:viewportHeight="200">
<path
android:name="start"
android:pathData="M100 4 l-100 192 l192 0 l-92,-194"
android:strokeWidth="3"
android:strokeColor="#a2d7dc"/>
</vector>
动画文件代码(这个比较简单就不一一介绍了)。
<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="4000"
android:propertyName="trimPathStart"
android:repeatCount="infinite"
android:repeatMode="reverse"
android:valueFrom="1"
android:valueTo="0"
android:valueType="floatType">
</objectAnimator>
<?xml version="1.0" encoding="utf-8"?>
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:drawable="@drawable/你的svg名称">
<target
android:animation="@animator/你的动画名称"
android:name="start"></target>
</animated-vector>
<ImageView
android:id="@+id/iv"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"
app:srcCompat="@drawable/taiji_anim" />
记得在根布局里加上:xmlns:app="http://schemas.android.com/apk/res-auto"
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView anim_path;
private Drawable drawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
anim_path = (ImageView) findViewById(R.id.iv);
anim_path.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.iv:
startAnim(anim_path);
break;
}
}
/**
* 启动动画
*
* @param iv
*/
private void startAnim(ImageView iv) {
drawable = iv.getDrawable();
if (drawable instanceof Animatable) {
((Animatable) drawable).start();
}
}
}
svg下载:阿里图库 svg转换为VectorDrawable工具:http://inloop.github.io/svg2android/