理解VectorDrawable轨迹动画中的trimPathStart和trimPathEnd属性

来源:互联网 发布:初级会计题库软件 编辑:程序博客网 时间:2024/05/22 14:45

首先定义一个VectorDrawable文件,名为search,为了简单,从左到右画一条线即可:

<vector xmlns:android="http://schemas.android.com/apk/res/android"    android:height="24dp"    android:viewportHeight="24.0"    android:viewportWidth="24.0"    android:width="24dp">  <path      android:name="line"      android:strokeColor="#FF000000"      android:strokeWidth="1.5"      android:pathData="M0,20 L24,20"/></vector>

再定义一个属性动画的XML文件,名为anim_search_line:

<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"    android:duration="2000"    android:propertyName="trimPathEnd"    android:valueFrom="1"    android:valueTo="0"    android:valueType="floatType"    />


定义一个animated-vector,文件名为animated_search,把属性动画和VectorDrawable的路径对象绑定:

<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"    android:drawable="@drawable/search">  <target      android:animation="@animator/anim_search_line"      android:name="line"/></animated-vector>


最后,给ImageView配置animated-vector作为图像内容,Java代买中获取drawable并运行动画即可,注意,要使用app:srcCompat,而不是android:src

    <ImageView        android:id="@+id/anim_image"        android:layout_width="match_parent"        android:layout_height="240dp"        app:srcCompat="@drawable/animated_search"        android:onClick="startAnim"        />

轨迹动画的原理是通过属性动画改变path的trimPathStart和trimPathEnd属性,这两个属性表示对路径的截取:

trimPathStart 属性表示截掉 从起点到某个位置的部分,保留剩下的部分;

trimPathEnd 属性表示截掉 从某个位置到终点的部分,保留剩下的部分。

这两个属性中一般使用0~1的浮点数作为百分数来描述该位置,轨迹的起点位置是0%,轨迹的终点位置是100%,当然,其实使用大于1的数字也可以。

还有一个属性trimPathOffset,表示起点向终点方向发生的偏移量,同样用浮点数表示偏移位置所处的轨迹的百分比,起点发生偏移,终点也会随之发生偏移,可自行尝试。

知道了上面的内容,就能很好理解属性动画的定义产生的不同效果了:

【1】使用trimPathStart属性,valueFrom:0,valueTo:1

线条从起点缩短到终点,即初始截断部分是0%,从起点开始逐渐扩大到终点,达到100%。

【2】使用trimPathStart属性,valueFrom:1,valueTo:0

线条从终点增长到起点,即初始截断部分是100%,从终点开始逐渐缩小到起点,达到0%。

【3】使用trimPathEnd属性,valueFrom:0,valueTo:1

线条从起点增长到终点,即初始截断部分是100%,从起点开始逐渐缩小到终点,达到0%。

【4】使用trimPathEnd属性,valueFrom:1,valueTo:0

线条从终点缩短到起点,即初始截断部分是0%,从终点开始逐渐扩大到起点,达到100%。