Android开发

ValueAnimator的源码及插值器估值器相关解读

本文主要是介绍ValueAnimator的源码及插值器估值器相关解读,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

前言

本篇文章从动画的开始到结束,一个流程认识一下动画的源码。 解读一下源码中的类的关系。并说明下插值器估值器的关系。

问题

问题1:动画涉及同时多个动画已经动画数据存储结构。 问题2:从开始到结束代码的流程是怎么走的。 问题3:插值器跟估值器是什么关系。

基础使用

mColorAnim = ValueAnimator.ofObject(new ArgbEvaluator(), 0, 0x80000000);//开始解读1
mColorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
   @Override
    public void onAnimationUpdate(ValueAnimator animation) {
       final int c = (Integer) animation.getAnimatedValue();
          mColor.setColor(c);
    }
});
mColorAnim.setDuration(2000);
mColorAnim.start(); //开始解读2
复制代码

源码解读

ValueAnimator.ofObject

public static ValueAnimator ofObject(TypeEvaluator evaluator, Object... values) {
        ValueAnimator anim = new ValueAnimator();
        anim.setObjectValues(values); //关键1
        anim.setEvaluator(evaluator); //关键2
        return anim;
    }
复制代码

这个方法创建了一个ValueAnimator对象并设置了我们传入的三个参数值.

先看一下setObjectValues

PropertyValuesHolder[] mValues;
...
public void setObjectValues(Object... values) {
            // mValues还没有初始化
  if (mValues == null || mValues.length == 0) {
    setValues(PropertyValuesHolder.ofObject("", null, values)); //关键点1
    }
        ....
        // New property/values/target should cause re-initialization prior to starting
        mInitialized = false;
    }
复制代码

这里先来看一下PropertyValuesHolder.ofObject("", null, values)返回了什么东西先

PropertyValuesHolder类
PropertyValuesHolder{ 
// 对应三个参数 "", null, values
public static PropertyValuesHolder ofObject(String propertyName, TypeEvaluator evaluator,Object... values) {
        PropertyValuesHolder pvh = new PropertyValuesHolder(propertyName);
        pvh.setObjectValues(values);//关键点1
        pvh.setEvaluator(evaluator);
        return pvh;
    }
public void setObjectValues(Object... values) {
        mValueType = values[0].getClass();//获取到传入值得类型。
        mKeyframes = KeyframeSet.ofObject(values);//关键点2
        if (mEvaluator != null) { //传入的是空 所以没有设置
            mKeyframes.setEvaluator(mEvaluator);
        }
    }
}
--------------------------------------------------------------------------------------------------------
KeyframeSet类
KeyframeSet{
public static KeyframeSet ofObject(Object... values) {
        int numKeyframes = values.length;
        ObjectKeyframe keyframes[] = new ObjectKeyframe[Math.max(numKeyframes,2)];
        if (numKeyframes == 1) {
            keyframes[0] = (ObjectKeyframe) Keyframe.ofObject(0f);
            keyframes[1] = (ObjectKeyframe) Keyframe.ofObject(1f, values[0]);
        } else {  //我们最开始传入的值是(0,0x8000000)这里numKeyframes=2 因此我们这里的keyframes[2]
            keyframes[0] = (ObjectKeyframe) Keyframe.ofObject(0f, values[0]);//关键3
            for (int i = 1; i < numKeyframes; ++i) {
                keyframes[i] = (ObjectKeyframe) Keyframe.ofObject((float) i / (numKeyframes - 1), values[i]);
            }
        }
        return new KeyframeSet(keyframes);
    }
}
--------------------------------------------------------------------------------------------------------
ObjectKeyframe类
ObjectKeyframe extends Keyframe {
Object mValue;
public static Keyframe ofObject(float fraction, Object value) {
        return new ObjectKeyframe(fraction, value);//关键4
    }
}
//关键5
ObjectKeyframe(float fraction, Object value)  Keyframe{
  mFraction = fraction;
  mValue = value;
  mHasValue = (value != null);
  mValueType = mHasValue ? value.getClass() : Object.class;
}
复制代码

由上面可以看到 PropertyValuesHolder.ofObject("", null, values)返回了一个PropertyValuesHolder对象,PropertyValuesHolder包含了我们Keyframes

Keyframes是一个数组,根据你传入的ValueAnimator.ofObject(new ArgbEvaluator(), 0, 0x80000000);传入的0, 0x80000000多少对应创建相对数量的Keyframe,(如果是传入一个则会产生2个Keyframe

Keyframe的作用就是存储 mFraction分数信息mValue 数值信息 mValueType 类型信息

image.png

返回上面最开始的anim.setEvaluator(evaluator); //关键2

    public void setEvaluator(TypeEvaluator value) {
        if (value != null && mValues != null && mValues.length > 0) {
            mValues[0].setEvaluator(value);
        }
    }
------------------------------------------------------------------------------------------------------------------
PropertyValuesHolder类
PropertyValuesHolder {
 public void setEvaluator(TypeEvaluator evaluator) {
        mEvaluator = evaluator;
        mKeyframes.setEvaluator(evaluator);
    }
}
复制代码

PropertyValuesHolderKeyframeSet存入该Evaluator

阶段性大致小结从下图可以大致看出各个类的功能

回答问题1:多种动画怎么处理以及每帧数据存储的结构.png

mColorAnim.start(); //开始解读2

public void start() {
  start(false);
}
----------------------------------------------------------------------
private void start(boolean playBackwards) {
mReversing = playBackwards;
mStarted = true;
mPaused = false;
mRunning = false;
....标记位记录等工作
addAnimationCallback(0);//关键1 
if (mStartDelay == 0...){
 startAnimation();//关键2
if (mSeekFraction == -1) {
setCurrentPlayTime(0);}}}
复制代码

关键1:等看完关键2再回过头看 关键2:先看一下回调的 startAnimation();

private void startAnimation() {
        .....
        mAnimationEndRequested = false;
        initAnimation(); //关键1
        mRunning = true;
        if (mSeekFraction >= 0) {
            mOverallFraction = mSeekFraction;
        } else {
            mOverallFraction = 0f;
        }
        if (mListeners != null) {
            notifyStartListeners();
        }
    }

 void initAnimation() {
        if (!mInitialized) {
            int numValues = mValues.length;
            for (int i = 0; i < numValues; ++i) {
                mValues[i].init();//关键2   mValues 是 PropertyValuesHolder类型的
            }
            mInitialized = true;
        }
    }
---------------------------------------------------
PropertyValuesHolder类
PropertyValuesHolder{
private static final TypeEvaluator sIntEvaluator = new IntEvaluator();
private static final TypeEvaluator sFloatEvaluator = new FloatEvaluator();
void init() {
        if (mEvaluator == null) {
            mEvaluator = (mValueType == Integer.class) ? sIntEvaluator :
                    (mValueType == Float.class) ? sFloatEvaluator :
                    null;
        }
        if (mEvaluator != null) {
            mKeyframes.setEvaluator(mEvaluator);
        }
    }
}
复制代码

这里是做了一些开始状态的初始化,然后mEvaluator估值器根据你是否有传入,没有传入的话根据你之前传入的值得类型对应给你设置估值器。仅当Integer、Float类型的才会帮你自动设置估值器。

看回上面关键1:addAnimationCallback(0);

ValueAnimator类
ValueAnimator{
 private void addAnimationCallback(long delay) {
      ....
        getAnimationHandler().addAnimationFrameCallback(this, delay);
    }
}
--------------------------------------------------------------------------------------------------------
AnimationHandler类
public class AnimationHandler {
public void addAnimationFrameCallback(final AnimationFrameCallback callback, long delay) {
        if (mAnimationCallbacks.size() == 0) {
            getProvider().postFrameCallback(mFrameCallback);//关键1 getProvider返回 MyFrameCallbackProvider
        }
        if (!mAnimationCallbacks.contains(callback)) {
            mAnimationCallbacks.add(callback); 
        }
       ......    }}

    private AnimationFrameCallbackProvider getProvider() {
        if (mProvider == null) {
            mProvider = new MyFrameCallbackProvider();
        }
        return mProvider;
    }
------------------------------------------------------------------------------------------------------------------------
MyFrameCallbackProvider类
MyFrameCallbackProvider implements AnimationFrameCallbackProvider {
 final Choreographer mChoreographer = Choreographer.getInstance();
 @Override
  public void postFrameCallback(Choreographer.FrameCallback callback) {
            mChoreographer.postFrameCallback(callback);//关键2
        }
}
------------------------------------------------------------------------------------------------------------------------
Choreographer类
Choreographer{
 public void postFrameCallback(FrameCallback callback) {
        postFrameCallbackDelayed(callback, 0);//关键3
    }

 public void postFrameCallbackDelayed(FrameCallback callback, long delayMillis) {
          ...........
        postCallbackDelayedInternal(CALLBACK_ANIMATION,callback, FRAME_CALLBACK_TOKEN, delayMillis);//关键4
    }
 private void postCallbackDelayedInternal(int callbackType, Object action, Object token, long delayMillis) {
             ......
            synchronized (mLock) {
            final long now = SystemClock.uptimeMillis();
            final long dueTime = now + delayMillis; // 0 + now 
            mCallbackQueues[callbackType].addCallbackLocked(dueTime, action, token);//关键5
            if (dueTime <= now) {
                scheduleFrameLocked(now); //关键6
            } else {
            ......}}}

 private void scheduleFrameLocked(long now) {
        if (!mFrameScheduled) {
            mFrameScheduled = true;
            if (USE_VSYNC) { // USE_VSYNC = true
              ....
                if (isRunningOnLooperThreadLocked()) {
                    scheduleVsyncLocked();//关键7
                }  }
              ......}}  }
    @UnsupportedAppUsage
 private void scheduleVsyncLocked() {
    mDisplayEventReceiver.scheduleVsync();//关键8
    }
-------------------------------------------------------------------------------------------------------------
DisplayEventReceiver类
DisplayEventReceiver{
   @FastNative
    private static native void nativeScheduleVsync(long receiverPtr);//关键10
public void scheduleVsync() {
            ............
            nativeScheduleVsync(mReceiverPtr);//关键9
    }
}
}
复制代码

跟到最后这里是一个Native方法。。。。。因为这块涉及到界面渲染的问题。当我们接受到一个新的Vsync信号的时候,它会回调FrameCallback接口的doFrame(long frameTimeNanos)函数。

我们从最开始的关键1getProvider().postFrameCallback(mFrameCallback)便传入了回调方法mFrameCallback 再到关键5 mCallbackQueues[callbackType].addCallbackLocked(dueTime, action, token); action 就是我们传入的mFrameCallback

代码如下

public void addCallbackLocked(long dueTime, Object action, Object token) {
            CallbackRecord callback = obtainCallbackLocked(dueTime, action, token);
            ....
        }
//创建 CallbackRecord 
private CallbackRecord obtainCallbackLocked(long dueTime, Object action, Object token) {
        CallbackRecord callback = mCallbackPool;
        if (callback == null) {
            callback = new CallbackRecord();
        } else {
            mCallbackPool = callback.next;
            callback.next = null;
        }
        callback.dueTime = dueTime;
        callback.action = action;
        callback.token = token;
        return callback;
    }
 private static final class CallbackRecord {
        public CallbackRecord next;
        public long dueTime;
        public Object action; // Runnable or FrameCallback
        public Object token;

        @UnsupportedAppUsage
        public void run(long frameTimeNanos) {
            if (token == FRAME_CALLBACK_TOKEN) {
                ((FrameCallback)action).doFrame(frameTimeNanos);//关键点1.1
            } else {
                ((Runnable)action).run();
            }
        }
    }
复制代码

当最终回调的时候会跑((FrameCallback)action).doFrame(frameTimeNanos);//关键点1.1 token == FRAME_CALLBACK_TOKEN

此时会回调到最开始AnimationHandler类中的 getProvider().postFrameCallback(mFrameCallback)的回调方法mFrameCallback

public class AnimationHandler {
    private final Choreographer.FrameCallback mFrameCallback = new Choreographer.FrameCallback() {
        @Override
        public void doFrame(long frameTimeNanos) {
            doAnimationFrame(getProvider().getFrameTime());//关键点1
            if (mAnimationCallbacks.size() > 0) {
                getProvider().postFrameCallback(this);
            }
        }
    };

private void doAnimationFrame(long frameTime) {
        long currentTime = SystemClock.uptimeMillis();
        final int size = mAnimationCallbacks.size(); //在第一个代码块中添加了一个callback进去,至少有一个。
        for (int i = 0; i < size; i++) {
            final AnimationFrameCallback callback = mAnimationCallbacks.get(i);
            ......
            if (isCallbackDue(callback, currentTime)) {
                callback.doAnimationFrame(frameTime); //关键2 //回看上面的可以知道frameTime这个类型是VaueAnimator
               ....................
            }
        }
      .....
    }
}
------------------------------------------------------------------------------------------------------------------------
public class ValueAnimator extends Animator implements AnimationHandler.AnimationFrameCallback {
public final boolean doAnimationFrame(long frameTime) {
      if (mStartTime < 0) {
            // 第一帧跑的逻辑.
            mStartTime = mReversing
                    ? frameTime
                    : frameTime + (long) (mStartDelay * resolveDurationScale());
        }

        // 处理 pause/resume的状态位
        if (mPaused) {
            mPauseTime = frameTime;
            removeAnimationCallback();//暂停的状态则取消该回调
            return false;
        } else if (mResumed) {
            mResumed = false;
          ......
        }
         .....
mLastFrameTime = frameTime;
final long currentTime = Math.max(frameTime, mStartTime);
boolean finished = animateBasedOnTime(currentTime);//关键点3

        if (finished) {
            endAnimation();
        }
        return finished;
    }
//计算对应的数值,这里处理动画重复等相关逻辑
boolean animateBasedOnTime(long currentTime) {
        boolean done = false;
        if (mRunning) {
            final long scaledDuration = getScaledDuration();
            final float fraction = scaledDuration > 0 ?
                    (float)(currentTime - mStartTime) / scaledDuration : 1f;
            final float lastFraction = mOverallFraction;
            final boolean newIteration = (int) fraction > (int) lastFraction;
            final boolean lastIterationFinished = (fraction >= mRepeatCount + 1) &&
                    (mRepeatCount != INFINITE);
          ......
            mOverallFraction = clampFraction(fraction);
            float currentIterationFraction = getCurrentIterationFraction(
                    mOverallFraction, mReversing);
            animateValue(currentIterationFraction);//关键点4
        }
        return done;
    }

    void animateValue(float fraction) {
        fraction = mInterpolator.getInterpolation(fraction);//对应插值器计算出分数值
        mCurrentFraction = fraction;
        int numValues = mValues.length;
        for (int i = 0; i < numValues; ++i) {
            mValues[i].calculateValue(fraction);//传入插值器的分值,后面交给估值器计算出最后的值
        }
        if (mUpdateListeners != null) {
            int numListeners = mUpdateListeners.size();
            for (int i = 0; i < numListeners; ++i) {
                mUpdateListeners.get(i).onAnimationUpdate(this);
            }
        }
    }
}
复制代码

mUpdateListeners.get(i).onAnimationUpdate(this);走到这里,我们在API使用的时候就可以回调到最后的值了, 以上就是我们找到的ValueAnimator的源码逻辑解读。

关于插值器跟估值器

void animateValue(float fraction) {
        fraction = mInterpolator.getInterpolation(fraction);//关键1 对应插值器计算出分数值
        mCurrentFraction = fraction;
        int numValues = mValues.length;
        for (int i = 0; i < numValues; ++i) {
            mValues[i].calculateValue(fraction);//关键2 传入插值器的分值,后面交给估值器计算出最后的值
        }
        if (mUpdateListeners != null) {
            int numListeners = mUpdateListeners.size();
            for (int i = 0; i < numListeners; ++i) {
                mUpdateListeners.get(i).onAnimationUpdate(this);
            }
        }
    }
复制代码

由上面的逻辑可以看到 fraction = mInterpolator.getInterpolation(fraction);//对应插值器计算出分数值先计算出插值器0-1区间的分值,再将此值传入到mValues[i].calculateValue(fraction);进行计算 关键1:代码代码如下

private static final TimeInterpolator sDefaultInterpolator =new AccelerateDecelerateInterpolator();
mInterpolator = sDefaultInterpolator 
fraction = mInterpolator.getInterpolation(fraction);//对应插值器计算出分数值
复制代码
public class AccelerateDecelerateInterpolator extends BaseInterpolator
        implements NativeInterpolatorFactory {
......
    public float getInterpolation(float input) {
        return (float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
    }
......
}
复制代码

现在来看一下估值器Evaluate的 关键2:代码代码如下

mValues[i].calculateValue(fraction); //传入插值器的分值,后面交给估值器计算出最后的值
---------------------------------------------------------------------
PropertyValuesHolder类
PropertyValuesHolder{
void calculateValue(float fraction) {
        Object value = mKeyframes.getValue(fraction);
        mAnimatedValue = mConverter == null ? value : mConverter.convert(value);
    }
}
复制代码

mKeyframes是什么类型的??

在上面 源码解读 ValueAnimator.ofObject可以看到setObjectValues ->PropertyValuesHolder.ofObject("", null, values)->setObjectValues 中可以看到 mKeyframesKeyframeSet类型的。

public class KeyframeSet implements Keyframes {
public Object getValue(float fraction) {
        // Special-case optimization for the common case of only two keyframes
        if (mNumKeyframes == 2) {
            if (mInterpolator != null) {
                fraction = mInterpolator.getInterpolation(fraction);
            }
            return mEvaluator.evaluate(fraction, mFirstKeyframe.getValue(),
                    mLastKeyframe.getValue());
        }
       .......
        Keyframe prevKeyframe = mFirstKeyframe;
        for (int i = 1; i < mNumKeyframes; ++i) {
            Keyframe nextKeyframe = mKeyframes.get(i);
            if (fraction < nextKeyframe.getFraction()) {
                final TimeInterpolator interpolator = nextKeyframe.getInterpolator();
                final float prevFraction = prevKeyframe.getFraction();
                float intervalFraction = (fraction - prevFraction) /
                    (nextKeyframe.getFraction() - prevFraction);
                // Apply interpolator on the proportional duration.
                if (interpolator != null) {
                    intervalFraction = interpolator.getInterpolation(intervalFraction);
                }
                return mEvaluator.evaluate(intervalFraction, prevKeyframe.getValue(),
                        nextKeyframe.getValue());
            }
            prevKeyframe = nextKeyframe;
        }
        // shouldn't reach here
        return mLastKeyframe.getValue();
    }
}
复制代码

从上面的逻辑你可以看到mEvaluator.evaluate(fraction,mFirstKeyframe.getValue(),mLastKeyframe.getValue());反正就是计算出各种对应的数值交给估值器去计算出最终的值并返回,将其赋值给上个代码块中的mAnimatedValue。 从这一点上我们可以看到 当我们在调用API接口的时候

mColorAnim = ValueAnimator.ofObject(new ArgbEvaluator(), 0, 0x80000000);//开始解读1
mColorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
   @Override
    public void onAnimationUpdate(ValueAnimator animation) {
       final int c = (Integer) animation.getAnimatedValue();
          mColor.setColor(c);
    }
});
mColorAnim.setDuration(2000);
mColorAnim.start(); //开始解读2
复制代码

animation.getAnimatedValue();这里获取到的是我们估值器计算出来的最终值。

小结:插值器是计算出分值,即0-1中间的分数值,估值器才是我们最后使用的属性值。估值器是由我们的属性值跟插值器的分数值相乘得出的一个我们此时此刻需要的属性值

这个代码是比较粗略的过了一遍动画的开始到结束,然后确定出来动画的一些协助类。很多细节的东西并没有讲出来,比如涉及到中间的Vsyn回调屏幕渲染的问题。这个很多东西讲的,如果在代码中一个个说的话,那实在太长了。下次再看看那个屏幕渲染的文章再写一篇博文吧。

这篇关于ValueAnimator的源码及插值器估值器相关解读的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!