1、自定义Interpolator
这是LinearInterpolator的源码
- public class LinearInterpolator implements Interpolator {
- public LinearInterpolator() {
- }
- public LinearInterpolator(Context context, AttributeSet attrs) {
- }
- public float getInterpolation(float input) {
- return input;
- }
- }
- public interface Interpolator extends TimeInterpolator {
- }
public interface TimeInterpolator { float getInterpolation(float var1); }float getInterpolation(float percent)这个方法的参数为当前动画的进度,范围0~1,这个进度只于时间有关,和其它没有关系。返回值表示当前实际想要显示的进度 取值可以超过1也可以小于0,超过1表示已经超过目标值,小于0表示小于开始位置。
- ublic class LinearInterpolator implements Interpolator {
- …………
- public float getInterpolation(float input) {
- return input;
- }
- } 、
- public class MyInterploator implements TimeInterpolator {
- @Override
- public float getInterpolation(float input) {
- return 1-input;
- }
- }
我们先不讲什么是Evaluator,我们先来看一张图:
这幅图讲述了从定义动画的数字区间到通过AnimatorUpdateListener中得到当前动画所对应数值的整个过程。下面我们对这四个步骤具体讲解一下:
(1)、ofInt(0,400)表示指定动画的数字区间,是从0运动到400;
(2)、加速器:上面我们讲了,在动画开始后,通过加速器会返回当前动画进度所对应的数字进度,但这个数字进度是百分制的,以小数表示,如0.2
(3)、Evaluator:我们知道我们通过监听器拿到的是当前动画所对应的具体数值,而不是百分制的进度。那么就必须有一个地方会根据当前的数字进度,将其转化为对应的数值,这个地方就是Evaluator;Evaluator就是将从加速器返回的数字进度转成对应的数字值。所以上部分中,我们讲到的公式:
- 当前的值 = 100 + (400 - 100)* 显示进度
(4)、监听器:我们通过在AnimatorUpdateListener监听器使用animation.getAnimatedValue()函数拿到Evaluator中返回的数字值。
讲了这么多,Evaluator其实就是一个转换器,他能把小数进度转换成对应的数值位置
- /**
- * This evaluator can be used to perform type interpolation between <code>int</code> values.
- */
- public class IntEvaluator implements TypeEvaluator<Integer> {
- /**
- * This function returns the result of linearly interpolating the start and end values, with
- * <code>fraction</code> representing the proportion between the start and end values. The
- * calculation is a simple parametric calculation: <code>result = x0 + t * (v1 - v0)</code>,
- * where <code>x0</code> is <code>startValue</code>, <code>x1</code> is <code>endValue</code>,
- * and <code>t</code> is <code>fraction</code>.
- *
- * @param fraction The fraction from the starting to the ending values
- * @param startValue The start value; should be of type <code>int</code> or
- * <code>Integer</code>
- * @param endValue The end value; should be of type <code>int</code> or <code>Integer</code>
- * @return A linear interpolation between the start and end values, given the
- * <code>fraction</code> parameter.
- */
- public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
- int startInt = startValue;
- return (int)(startInt + fraction * (endValue - startInt));
- }
- }
其中fraction就是加速器中的返回值,表示当前动画的数值进度,百分制的小数表示。
startValue和endValue分别对应ofInt(int start,int end)中的start和end的数值;
比如我们假设当我们定义的动画ofInt(100,400)进行到数值进度20%的时候,那么此时在evaluate函数中,fraction的值就是0.2,startValue的值是100,endValue的值是400;理解上应该没什么难度。