ValueAnimation 原理分析

基本用法:

设置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的调用链从 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;
    }
复制代码

经过三角函数变换,输入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);
    }
复制代码

转载于:https://juejin.im/post/5c9841775188252d93208755

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值