设置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()
}
复制代码
onAnimationUpdate
是如何实现的?animatedValue
是如何计算出来的?onAnimationUpdate
的调用链从
Choreographer
中的
FrameDisplayEventReceiver
开始、经由
AnimationHandler
、一直传到
ValueAnimator
。
咱们先来看下AnimationHandler
。app
/**
* 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
完成周期性回调。 AnimationHandler
与 ValueAnimator
(implements AnimationHandler.AnimationFrameCallback) 的交互主要有如下几点:ide
addAnimationCallback
: 动画开始时,ValueAnimator
将本身做为AnimationFrameCallback注册到AnimationHandler中。removeAnimationCallback
: 动画结束时,ValueAnimator
移除本身在AnimationHandler
中的注册。
咱们再来看看FrameDisplayEventReceiver的代码。 函数
FrameDisplayEventReceiver
继承自抽象类
DisplayEventReceiver
,
FrameDisplayEventReceiver
有如下几个关键方法:
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;
}
复制代码
0.5PI*sin(PI*(x+1))
)。
PropertyValuesHolder#calculateValue
void calculateValue(float fraction) {
Object value = mKeyframes.getValue(fraction);
mAnimatedValue = mConverter == null ? value : mConverter.convert(value);
}
复制代码