ValueAnimation 原理分析

基本用法:

設置keyFrameValues、duration、updateListener 啓動動畫後,AnimatorUpdateListener#onAnimationUpdate()方法每隔 1/60s 都會被回調一次,能夠從animation中拿到當前幀對應的數據。bash

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

咱們先來看下AnimationHandlerapp

/**
 * 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) 的交互主要有如下幾點:ide

  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的源碼oop

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()動畫

簡化一下就是:ui

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

經過上面的循環,onVsync()每隔1/60s會回調一次,方法調用層層傳遞,最後就傳遞到了咱們重寫的AnimatorUpdateListener#onAnimationUpdate()中。 因爲doFrame()中會對時間作判斷,動畫結束後不會調scheduleVsync(),因此循環在動畫結束就中止了。spa

總結
綜上,動畫幀回調的傳遞過程以下。

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);
    }
複製代碼
相關文章
相關標籤/搜索