引言
学习属性动画时,曾今提到过TypeEvaluater,Interpolator两个类,这篇博客对这两个类做一些简单的学习。话不多说,进入正题。
TypeEvaluater
TypeEvaluater是属性动画的值计算器,在学习属性动画时,必然会用到的一个方法就是ValueAnimator的addUpdateListener()方法,即添加动画监听器,监听器需要实现一个方法即public void onAnimationUpdate(ValueAnimator valueAnimator),通过这个方法我们可以拿到动画变化过程中的值即 valueAnimator.getAnimatedValue(),那么这个值是怎么计算出来的呢?就是TypeEvaluater的职责了。
源码
public interface TypeEvaluator {
T evaluate(float fraction, T startValue, T endValue);
}
可以看出 TypeEvaluater就是一个接口,只有一个方法,用于计算当前时间的动画值。系统默认的实现是这样的,:
startValue + fraction * (endValue - startValue)
系统提供了三种类型的:FloatEvaluator、IntEvaluator、ArgbEvaluator
自定义
下面是一个简单的TypeEvaluater自定义的类
/*对象动画*/
class MyAnimObject{
int value;
public MyAnimObject(int value){
this.value = value;
}
}
/*对象动画算值器*/
class MyAnimObjectEvaluator implements TypeEvaluator{
@Override
public MyAnimObject evaluate(float v, MyAnimObject myAnimObject, MyAnimObject t1) {
int oldValue = myAnimObject.value;
int newValue = t1.value;
int res = (int)((oldValue + newValue)*v)*2;
MyAnimObject animObject = new MyAnimObject(res);
return animObject;
}
}
Interpolator
关于Interpolator的解释这里不再重述,前面的博客中已经提到过,就不再累赘,不了解的同学可以点击这里。
源码
它本身是一个空接口,如下,继承自TimeInterpolator。
public interface Interpolator extends TimeInterpolator {
// A new interface, TimeInterpolator, was introduced for the new android.animation
// package. This older Interpolator interface extends TimeInterpolator so that users of
// the new Animator-based animations can use either the old Interpolator implementations or
// new classes that implement TimeInterpolator directly.
}
那么来看一下TimeInterpolator的代码
public interface TimeInterpolator {
/**
* Maps a value representing the elapsed fraction of an animation to a value that represents
* the interpolated fraction. This interpolated value is then multiplied by the change in
* value of an animation to derive the animated value at the current elapsed animation time.
*
* @param input A value between 0 and 1.0 indicating our current point
* in the animation where 0 represents the start and 1.0 represents
* the end
* @return The interpolation value. This value can be more than 1.0 for
* interpolators which overshoot their targets, or less than 0 for
* interpolators that undershoot their targets.
*/
float getInterpolation(float input);
}
可以看到只有一个方法即float getInterpolation(float input),就是计算动画的变化率(自己的理解),input是当前的时间节点,开始时间为0,结束时间为1。所以要写出自己想要的变化率,只需要继承这个接口,重写这个方法就好了。
自定义
实现抛物线式的变化率。
class DiyInterpolator implements Interpolator{
@Override
public float getInterpolation(float input) {
return input*input; //y = x^2;
}
}
结尾
这篇博客就讲这么多,欢迎大家加群讨论