ValueAnimation 原理分析

1,251 阅读3分钟

基本用法:

设置keyFrameValues、duration、updateListener 启动动画后,AnimatorUpdateListener#onAnimationUpdate()方法每隔 1/60s 都会被回调一次,可以从animation中拿到当前帧对应的数据。

    private fun startAnimator() {
        val animator = ValueAnimator.ofFloat(0f, 1f)
        animator.duration = 1000
        animator.repeatCount = 10
        animator.repeatMode = ValueAnimator.REVERSE
        animator.interpolator = object : TimeInterpolator {
            override fun getInterpolation(input: Float): Float {
                return (Math.cos((input + 1) * Math.PI) / 2.0f).toFloat() + 0.5f //AccelerateDecelerate
            }
        }
        animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener {
            override fun onAnimationUpdate(animation: ValueAnimator) {
                println(animation.animatedValue)
            }
        })
        animator.start()
    }

疑问

  1. 每隔1/60s回调一次onAnimationUpdate是如何实现的?
  2. animatedValue是如何计算出来的?

onAnimationUpdate 调用的逻辑

onAnimationUpdate调用链
(上面的调用链有点长,不要慌,先看大概涉及了哪些类,后面再详细分析具体的方法。) 从上图可以看到,onAnimationUpdate的调用链从Choreographer中的FrameDisplayEventReceiver开始、经由AnimationHandler、一直传到ValueAnimator

我们先来看下AnimationHandler

/**
 * This custom, static handler handles the timing pulse that is shared by all active
 * ValueAnimators. This approach ensures that the setting of animation values will happen on the
 * same thread that animations start on, and that all animations will share the same times for
 * calculating their values, which makes synchronizing animations possible.
 *
 * The handler uses the Choreographer by default for doing periodic callbacks. A custom
 * AnimationFrameCallbackProvider can be set on the handler to provide timing pulse that
 * may be independent of UI frame update. This could be useful in testing.
 *
 * @hide
 */
public class AnimationHandler{

AnimationHandler 是一个全局单例,被所有ValueAnimators共享,以便实现动画同步,默认使用Choreographer完成周期性回调。 AnimationHandlerValueAnimator(implements AnimationHandler.AnimationFrameCallback) 的交互主要有以下几点:

  1. addAnimationCallback: 动画开始时,ValueAnimator 将自己作为AnimationFrameCallback注册到AnimationHandler中。
  2. removeAnimationCallback: 动画结束时,ValueAnimator 移除自己在AnimationHandler中的注册。
    ValueAnimator实现的回调被传到AnimationHandler中了,经过一系列调用传递,最终走到了Choreographa中的FrameDisplayEventReceiver#onVsync()

我们再来看看FrameDisplayEventReceiver的代码。

FrameDisplayEventReceiver 继承自抽象类 DisplayEventReceiverFrameDisplayEventReceiver有以下几个关键方法:

  • scheduleVsync(): Schedules a single vertical sync pulse. 用白话说就是,下次v-sync的时候通知我(回调onVsync)。
  • onVsync(): Called when a vertical sync pulse is received.
/**
 * Provides a low-level mechanism for an application to receive display events
 * such as vertical sync.
 * ...
 */
public abstract class DisplayEventReceiver {
    public DisplayEventReceiver(Looper looper, int vsyncSource) {
        // ...
        mReceiverPtr = nativeInit(new WeakReference<DisplayEventReceiver>(this), mMessageQueue,
                vsyncSource);
        //...
    }
    
    public void scheduleVsync() {
        // ...
        nativeScheduleVsync(mReceiverPtr);
    }
    
    // Called from native code.
    private void dispatchVsync(long timestampNanos, int builtInDisplayId, int frame) {
        onVsync(timestampNanos, builtInDisplayId, frame);
    }
    
    /**
     * Called when a vertical sync pulse is received.
     * The recipient should render a frame and then call {@link #scheduleVsync}
     * to schedule the next vertical sync pulse.
    public void onVsync(long timestampNanos, int builtInDisplayId, int frame) {
    }

FrameDisplayEventReceiver的源码

    private final class FrameDisplayEventReceiver extends DisplayEventReceiver
            implements Runnable {
        // ...
        @Override
        public void onVsync(long timestampNanos, int builtInDisplayId, int frame) {
            // ...
            Message msg = Message.obtain(mHandler, this);
            msg.setAsynchronous(true);
            mHandler.sendMessageAtTime(msg, timestampNanos / TimeUtils.NANOS_PER_MS);
        }

        @Override
        public void run() {
            mHavePendingVsync = false;
            doFrame(mTimestampNanos, mFrame);
        }
    }
    void doFrame(long frameTimeNanos, int frame) {
        final long startNanos;
        synchronized (mLock) {
           // ...

        if (frameTimeNanos < mLastFrameTimeNanos) {
            //...
            scheduleVsyncLocked();
            return;
        }
    }
    
    private void scheduleVsyncLocked() {
        mDisplayEventReceiver.scheduleVsync();
    }

结合前面的DisplayEventReceiver的源码分析我们知道scheduleVsync最后会触发onVsync,所以完整的流程是:

onVsync() -> mHandler.sendMessageAtTime() -> run() -> doFrame() -> scheduleVsyncLocked -> mDisplayEventReceiver.scheduleVsync() -> onVsync()

简化一下就是:

onVsync() -> doFrame() -> onVsync()

通过上面的循环,onVsync()每隔1/60s会回调一次,方法调用层层传递,最后就传递到了我们重写的AnimatorUpdateListener#onAnimationUpdate()中。 由于doFrame()中会对时间做判断,动画结束后不会调scheduleVsync(),所以循环在动画结束就停止了。

总结
综上,动画帧回调的传递过程如下。

animatedValue的计算逻辑

这是我们在动画执行过程中每一帧计算值的方法

注:调用链是doAnimationFrame() -> animateBasedOnTime() -> aniateValue()

    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); // 计算动画value
        }
        if (mUpdateListeners != null) {
            int numListeners = mUpdateListeners.size();
            for (int i = 0; i < numListeners; ++i) {
                mUpdateListeners.get(i).onAnimationUpdate(this);
            }
        }
    }

可以看到在计算的时候,先用mInterpolator对fraction进行处理。 默认是AccelerateDecelerateInterpolator

public float getInterpolation(float input) {
        return (float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
    }

Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f
经过三角函数变换,输入fraction的输出结果不再是线性,而是先加速再减速的效果(导数为0.5PI*sin(PI*(x+1)))。

PropertyValuesHolder#calculateValue

    void calculateValue(float fraction) {
        Object value = mKeyframes.getValue(fraction);
        mAnimatedValue = mConverter == null ? value : mConverter.convert(value);
    }