学更好的别人,
做更好的自己。
——《微卡智享》
Android自定义动画
前面好几篇都是专门介绍了Android的动画效果,这一章我们就根据学习的内容做一个实战效果,达到学以致用的效果。
实现效果
上面视频中可以看到,我们把视频开始的那串文本“微卡智享,学更好的别人,做更好的自己”通过动画的效果逐一滚动的显示出来,并且在显示的过程中字体在不断的放大和向右下移动,当显示完后再按原路径显示回去。
实现思路
1. 定义一个PointText类,用于记录输入的字符串并进行拆分为数组,加入移动的偏移量和当前执行动画的位置。
2. 定义TypeEvaluator类,重写evaluate的方法,根据输入的参数计算出PointText类中的对应值。
3. 创建ValueAnimator动画,在addUpdateListener事件中得到的PointText的返回值对我们的Textview进行重新定位和显示
4. 设置动画属性,并播放动画
代码实现
微卡智享
PointText类
package dem.vac.animation;
public class PointText {
//当前偏移量
public int curoffset;
//当前是第几个文字
public int curtext;
//显示文字数组
public char[] chararray;
public PointText(String str) {
//将传入的字符串拆为成Char数组
chararray=str.toCharArray();
curtext=0;
curoffset=0;
}
//根据当前为第几个文字进行输出
public String getChar() {
return String.valueOf(chararray[curtext]);
}
}
上面的类来说没有什么特别的,主要的知识点就是看看String怎么转为Char数据,还有Char数组怎么返回String
PointTextEvaluator
package dem.vac.animation;
import android.animation.TypeEvaluator;
public class PointTextEvaluator implements TypeEvaluator {
private PointText mPointText;
public PointTextEvaluator(PointText pointText) {
mPointText=pointText;
}
@Override
public Object evaluate(float v, Object int1, Object int2) {
int starti=(int) int1;
int endi=(int) int2;
//计算当前位置偏移量
mPointText.curoffset=(int) (starti + v * (endi - starti));
//计算当前应该显示字的顺序
mPointText.curtext=(int) (0 + v * (mPointText.chararray.length));
if (mPointText.curtext == mPointText.chararray.length) {
mPointText.curtext=mPointText.chararray.length - 1;
}
return mPointText;
}
}
这里的TypeEvaluator我没用到泛型,是因为我的输入参数为两个integer的类型,用于设置输入的移动的开始和结束距离,而返回的参数就是我们的PointText的类,所以就用的默认Object的类型后进入强制转换。
ValueAnimator
private void InitPointText(String text) {
//获取文本框初始的坐标XY
final float oldx=tvshow.getX();
final float oldy=tvshow.getY();
//初始化PointText
PointText pointText=new PointText(text);
//定义ValueAnimator动画
ValueAnimator animator=ValueAnimator.ofObject(new PointTextEvaluator(pointText), 1, 200);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
PointText tmppt=(PointText) valueAnimator.getAnimatedValue();
//设置文本框当前要显示的文字
tvshow.setText(tmppt.getChar());
//设置文本框当前的坐标
tvshow.setX(oldx + tmppt.curoffset);
tvshow.setY(oldy + tmppt.curoffset);
//设置当前文本框的缩放大小
tvshow.setScaleX(tmppt.curtext + 1);
tvshow.setScaleY(tmppt.curtext + 1);
//更新显示动画
tvshow.requestLayout();
}
});
//设置动画的速率,用LinearInterpolator为平均显示
animator.setInterpolator(new LinearInterpolator());
//设置播放时间
animator.setDuration(5000);
//设置播放完后倒序播放回来
animator.setRepeatCount(1);
animator.setRepeatMode(ValueAnimator.REVERSE);
animator.start();
}
整个ValueAnimator的创建代码,首先定义了PointText的类,然后在通过ValueAnimator.ofObject再创建了PointTextEvaluator,其中移动的数值参数设置为了1到50,在addUpdateListener事件中通过返回的PointText的类用于处理TextView应该显示的文字和移动的位置,最后设置了一下播放完后再按倒序的方式回放。
播放动画
这样就实现在我们文章开始视频的效果了,下面是做了个Gif的显示动图