前言
属性动画作为现在开发中常用的动画,我们需要对他有比较详细的了解,才能够在开发中随心和高效的使用。在了解属性动画之前我们先了解Android前期的视图动画
一、视图动画
视图动画是为View对象添加动画效果的功能,如果想为非对象动画添加效果,则必须自己实现自己的代码才能做到。
视图动画仅公开 对象的部分方面来供您添加动画效果,比如旋转、错放、移动
视图动画只是在绘制视图的位置进行修改,而不会修改实际的视图本身。例如,为某个按钮添加了移动动画,该按钮会正确绘制,但能够点击按钮的实际位置并回修更改,我们必须通过实现自己的逻辑来处理此事件。
二、属性动画
2.1 属性动画概览
属性动画是系统提供的一个强健框架。可以定义一个随时间更改任何对象属性的的动画,属性动画会在指定时长内更改属性(对象中的字段)的值。
属性动画特性:
- 时长:指定动画执行的时长,默认为300毫秒
- 时间插值:更多动画当前已经播放的时长来计算属性的值
- 重复计数和行为:是否重复播放动画以及重复播放动画次数,是否发现播放动画。
- Animator集:将多个动画分成多个逻辑,他们可以一起播放、按顺序播放或者在指定延迟后播放
- 帧刷新延迟:您可以指定动画帧的刷新频率。默认设置为每 10 毫秒刷新一次,但应用刷新帧的速度最终取决于整个系统的繁忙程度以及系统为底层计时器提供服务的速度
2.2 属性动画使用
属性的动画的相关类在 android.anmition 中,视图动画的相关类在android.view.animation包中,我们在使用的过程中可以留心观察一下。接下来我们了解属性动画的使用。
2.2.1 对View对象设置属性动画
下面结合ObjectAnimator以及BounceInterpolator来完成一个view的translationY的移动动画
private void startAnimation() {
int[] tarViewLocation = new int[2];
int[] endViewLocation = new int[2];
targetView.getLocationInWindow(tarViewLocation);
viewEnd.getLocationInWindow(endViewLocation);
float endLocation = endViewLocation[1] - tarViewLocation[1] - targetView.getHeight();
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(targetView, "translationY", 0f, endLocation);
objectAnimator.setInterpolator(new BounceInterpolator());
objectAnimator.setDuration(2000);
objectAnimator.start();
}

2.2.2 直接使用属性动画特性
我们了解属性动画处理作用于View视图以外,还可以单独使用,我们可以监听相关的值的变化来处理我们自身的逻辑。下面我们通过ValueAnimator实现一个水杯里装水的效果。
第一步: 自定一个WaterView,完成水的绘制
public class WaterView extends View {
private static final int DEFAULT_COLOR = Color.BLUE;
private int color;
//水位高度-单位像素
private int waterPx;
//水位结束高度
private int waterEndYpx;
//视图宽
private int viewWidth;
//视图宽
private int viewHeight;
private Paint paintWater;
//波浪path
private Path pathWave;
//波浪
private int waveWidth;
//波浪高度 px
private int waveHeight = 20;
//当前绘制水位的起始Y坐标
private int currentDrawHeight;
//水位上升变化值
private int dy;
public WaterView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.WaterView, 0, 0);
try {
color = typedArray.getColor(R.styleable.WaterView_color, DEFAULT_COLOR);
} finally {
typedArray.recycle();
}
init();
}
private void init() {
paintWater = new Paint();
paintWater.setColor(color);
paintWater.setAntiAlias(true);
pathWave = new Path();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
viewWidth = w;
viewHeight = h;
waveWidth = viewWidth;
currentDrawHeight = viewHeight;
}
@Override
protected void onDraw(Canvas canvas) {
pathWave.reset();
if (currentDrawHeight == waterEndYpx) {
pathWave.moveTo(0, currentDrawHeight);
pathWave.lineTo(waveWidth, currentDrawHeight);
} else {
pathWave.moveTo(-waveWidth + dy, currentDrawHeight);
for (int i = -waveWidth; i < viewWidth + waveWidth; i += waveWidth) {
pathWave.rQuadTo(waveWidth / 4, -waveHeight, waveWidth / 2, 0);
pathWave.rQuadTo(waveWidth / 4, waveHeight, waveWidth / 2, 0);
}
}
pathWave.lineTo(viewWidth, viewHeight);
pathWave.lineTo(0, viewHeight);
if(waterPx > 0){
canvas.drawPath(pathWave, paintWater);
}
super.onDraw(canvas);
}
}
第二步: 添加属性动画,实施改变水位的高度
/**
* @param duration 动画执行时长
* @param waterHeight 水位高度,单位像素
*/
public void pourWater(long duration, int waterHeight) {
waterEndYpx = viewHeight - waterHeight;
waterPx = waterHeight;
start(duration);
}
private void start(long duration) {
ValueAnimator valueAnimator = ValueAnimator.ofInt(0, waterPx);
valueAnimator.setInterpolator(new AccelerateInterpolator());
valueAnimator.setDuration(duration);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
dy = (int) animation.getAnimatedValue();
currentDrawHeight = viewHeight - dy;
invalidate();
}
});
valueAnimator.start();
}
第三步: 效果图

2.3 属性动画工作原理
了解完属性的动画的概念和使用后,接下就是其核心的实现原理和本质,只有了解了背后的逻辑后,我们在开发中就能更随心所欲的使用。
2.3.1 了解ValueAnimatro的刷新机制
了解背后的原理就需要从源码入手,下面结合具体的使用来分析使用逻辑。
2.3.1.1 ValueAnimator对象的创建
我们可以通过下面的方法来创建ValueAnimator对象
ValueAnimator valueAnimator = ValueAnimator.ofInt(0, waterPx);
源码的实现:
public static ValueAnimator ofInt(int... values) {
ValueAnimator anim = new ValueAnimator();
anim.setIntValues(values);
return anim;
}
//设置int属性值
public void setIntValues(int... values) {
if (values == null || values.length == 0) {
return;
}
if (mValues == null || mValues.length == 0) {
setValues(PropertyValuesHolder.ofInt("", values));
} else {
PropertyValuesHolder valuesHolder = mValues[0];
valuesHolder.setIntValues(values);
}
// New property/values/target should cause re-initialization prior to starting
mInitialized = false;
}
//设置属性值
public void setValues(PropertyValuesHolder... values) {
int numValues = values.length;
mValues = values;
mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues);
for (int i = 0; i < numValues; ++i) {
PropertyValuesHolder valuesHolder = values[i];
mValuesMap.put(valuesHolder.getPropertyName(), valuesHolder);
}
// New property/values/target should cause re-initialization prior to starting
mInitialized = false;
}
ofInt()方法返回一个ValueAnimator对象,同时将values按照自己的方式存储起来,
2.3.1.2 设置动画执行时间
valueAnimator.setDuration(duration);
@Override
public ValueAnimator setDuration(long duration) {
if (duration < 0) {
throw new IllegalArgumentException("Animators cannot have negative duration: " +
duration);
}
mDuration = duration;
return this;
}
这个方法没有做什么操作,只是将动画的执行时间存储了起来
2.3.1.3 设置动画插值器
valueAnimator.setInterpolator(new AccelerateInterpolator());
private TimeInterpolator mInterpolator = sDefaultInterpolator;
private static final TimeInterpolator sDefaultInterpolator =
new AccelerateDecelerateInterpolator();
@Override
public void setInterpolator(TimeInterpolator value) {
if (value != null) {
mInterpolator = value;
} else {
mInterpolator = new LinearInterpolator();
}
}
动画系统默认使用的是AccelerateDecelerateInterpolator,该插值器的变化率在开始和结束时缓慢但在中间会加快。这里代码也没有做什么具体的逻辑。关于插值器的使用,后续在详细介绍,我们先了解整个属性动画的执行流程,然后再对各个点具体的深入分析。
2.3.1.4 执行动画
相关动画执行的要素设置完成后,需要执行动画,一般调用start()方法。
valueAnimator.start()
接下来看源码的实现逻辑:
@Override
public void start() {
start(false);
}
该方法没做什么操作,看内部的实现:
private void start(boolean playBackwards) {
if (Looper.myLooper() == null) {
throw new AndroidRuntimeException("Animators may only be run on Looper threads");
}
mReversing = playBackwards;
mSelfPulse = !mSuppressSelfPulseRequested;
......
//一些默认值设置
mStarted = true;
mPaused = false;
mRunning = false;
mAnimationEndRequested = false;
mLastFrameTime = -1;
mFirstFrameTime = -1;
mStartTime = -1;
//添加回调
addAnimationCallback(0);
if (mStartDelay == 0 || mSeekFraction >= 0 || mReversing) {
//没有延迟,初始化动画,并启动帧监听
startAnimation();
if (mSeekFraction == -1) {
setCurrentPlayTime(0);
} else {
setCurrentFraction(mSeekFraction);
}
}
}
默认mStartDelay为0,接下来进入startAnimation()方法
private void startAnimation() {
if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, getNameForTrace(),
System.identityHashCode(this));
}
mAnimationEndRequested = false;
initAnimation();
mRunning = true;
if (mSeekFraction >= 0) {
mOverallFraction = mSeekFraction;
} else {
mOverallFraction = 0f;
}
//通知startListeners
if (mListeners != null) {
notifyStartListeners();
}
}
void initAnimation() {
if (!mInitialized) {
int numValues = mValues.length;
for (int i = 0; i < numValues; ++i) {
mValues[i].init();
}
mInitialized = true;
}
}
startAnimation也没有做什么操作,做了初始化以及startListener的回调,没有其他操作 。到了这里,貌似没有看到动画是如何根据时间的流逝的执行过程,怎么办?
在start()方法中,还有一个方法没有分析,addAnimationCallback(),查看他的实现过程
private void addAnimationCallback(long delay) {
if (!mSelfPulse) {
return;
}
getAnimationHandler().addAnimationFrameCallback(this, delay);
}
public AnimationHandler getAnimationHandler() {
return mAnimationHandler != null ? mAnimationHandler : AnimationHandler.getInstance();
}
流程执行到了AnimationHandler,接下来分析AnimationHandler.getInstance()创建实现的过程
public final static ThreadLocal<AnimationHandler> sAnimatorHandler = new ThreadLocal<>();
public static AnimationHandler getInstance() {
if (sAnimatorHandler.get() == null) {
sAnimatorHandler.set(new AnimationHandler());
}
return sAnimatorHandler.get();
}
这里ThreadLocal的作用的存储的对象在当前Thread中,内部的实现是通过Thread的字段ThreadLocalMap来存储对应的值,保证存储的内容只供当前Thread使用。
AnimationHandler实例创建后,执行addAnimationFrameCallback()
/**
* Register to get a callback on the next frame after the delay.
*/
public void addAnimationFrameCallback(final AnimationFrameCallback callback, long delay) {
if (mAnimationCallbacks.size() == 0) {
getProvider().postFrameCallback(mFrameCallback);
}
if (!mAnimationCallbacks.contains(callback)) {
mAnimationCallbacks.add(callback);
}
if (delay > 0) {
mDelayedCallbackStartTime.put(callback, (SystemClock.uptimeMillis() + delay));
}
}
/**
* Register to get a callback on the next frame after the delay.
*/
public void addAnimationFrameCallback(final AnimationFrameCallback callback, long delay) {
if (mAnimationCallbacks.size() == 0) {
getProvider().postFrameCallback(mFrameCallback);
}
//没有延迟的情况,加入到mAnimationCallbacks列表中
if (!mAnimationCallbacks.contains(callback)) {
mAnimationCallbacks.add(callback);
}
if (delay > 0) {
mDelayedCallbackStartTime.put(callback, (SystemClock.uptimeMillis() + delay));
}
}
这里使用到了MyFrameCallbackProvider,接下来一下该类的信息
private class MyFrameCallbackProvider implements AnimationFrameCallbackProvider {
final Choreographer mChoreographer = Choreographer.getInstance();
@Override
public void postFrameCallback(Choreographer.FrameCallback callback) {
mChoreographer.postFrameCallback(callback);
}
@Override
public void postCommitCallback(Runnable runnable) {
mChoreographer.postCallback(Choreographer.CALLBACK_COMMIT, runnable, null);
}
@Override
public long getFrameTime() {
return mChoreographer.getFrameTime();
}
@Override
public long getFrameDelay() {
return Choreographer.getFrameDelay();
}
@Override
public void setFrameDelay(long delay) {
Choreographer.setFrameDelay(delay);
}
}
这里相关方法的操作是通过Choreographer来完成,到了这里其实也没有看出整个属性动画的刷新机制。其实在addAnimationFrameCallback的方法中,还有一个操作, getProvider().postFrameCallback(mFrameCallback);整个mFrameCallback其实Choreographer.FrameCallback 的实现类。代码如下:
private final Choreographer.FrameCallback mFrameCallback = new Choreographer.FrameCallback() {
@Override
public void doFrame(long frameTimeNanos) {
doAnimationFrame(getProvider().getFrameTime());
if (mAnimationCallbacks.size() > 0) {
getProvider().postFrameCallback(this);
}
}
};
这里的mFrameCallback执行了doAnimationFrame
private void doAnimationFrame(long frameTime) {
long currentTime = SystemClock.uptimeMillis();
final int size = mAnimationCallbacks.size();
for (int i = 0; i < size; i++) {
final AnimationFrameCallback callback = mAnimationCallbacks.get(i);
if (callback == null) {
continue;
}
if (isCallbackDue(callback, currentTime)) {
callback.doAnimationFrame(frameTime);
if (mCommitCallbacks.contains(callback)) {
getProvider().postCommitCallback(new Runnable() {
@Override
public void run() {
commitAnimationFrame(callback, getProvider().getFrameTime());
}
});
}
}
}
cleanUpList();
}
private void commitAnimationFrame(AnimationFrameCallback callback, long frameTime) {
if (!mDelayedCallbackStartTime.containsKey(callback) &&
mCommitCallbacks.contains(callback)) {
callback.commitAnimationFrame(frameTime);
mCommitCallbacks.remove(callback);
}
}
这里的mFrameCallback执行了doAnimationFrame,该方法又会执行AnimationFrameCallback的doAnimationFrame以及在下一帧屏幕刷新的时候执行,同时又去执行AnimationFrameCallback的commitAnimationFrame,而doAnimationFrame和commitAnimationFrame在ValueAnimator中具体实现。其中的熟悉过程稍后分析。到了这里基本就是刷新的流程了,这里根据用到了屏幕刷新机制,想了解具体实现过程的可以去看这篇文章。
属性动画刷新机制总结:
- 刷新动画的刷新机制是通过屏幕的刷新机制来实现的,将mFrameCallback 缓存到Choreographer的待执行队列里,并先底层注册监听下一个屏幕刷新信号事件。
- 当屏幕刷新信号到的时候,Choreographer的doFram()会将带执行队列里的工作取出来执行,此时就回调到了将mFrameCallback的doFrame()方法,再这个方法里面完成AnimationFrameCallback的doAnimationFrame()以及commitAnimationFrame();具体的的实现逻辑在ValueAnimaotor的doAnimationFrame和commitAnimationFrame完成。
2.3.2 了解ValueAnimatror的计算规则
2.3.2.1 分析执行流程
通过前面对ValueAnimator刷新机制的分析,我们了解到Choreographer.FrameCallback的doFrame()中会执行doAnimationFrame(),下面我们分析其中的执行原理
public final boolean doAnimationFrame(long frameTime) {
if (mStartTime < 0) {
//记录第一帧动画开始时间,从而才能在后面帧刷新的时候计算总执行时间
mStartTime = mReversing
? frameTime
: frameTime + (long) (mStartDelay * resolveDurationScale());
}
// 对暂停和重新开始的处理
if (mPaused) {
mPauseTime = frameTime;
//移除回调
removeAnimationCallback();
return false;
} else if (mResumed) {
mResumed = false;
if (mPauseTime > 0) {
// Offset by the duration that the animation was paused
mStartTime += (frameTime - mPauseTime);
}
}
if (!mRunning) {
if (mStartTime > frameTime && mSeekFraction == -1) {
return false;
} else {
mRunning = true;
startAnimation();
}
}
if (mLastFrameTime < 0) {
if (mSeekFraction >= 0) {
long seekTime = (long) (getScaledDuration() * mSeekFraction);
mStartTime = frameTime - seekTime;
mSeekFraction = -1;
}
mStartTimeCommitted = false; // allow start time to be compensated for jank
}
mLastFrameTime = frameTime;
final long currentTime = Math.max(frameTime, mStartTime);
boolean finished = animateBasedOnTime(currentTime);
if (finished) {
endAnimation();
}
return finished;
}
这个方法没有太多的逻辑,做了一些初始值的设置以及状态的控制,其中判断动画是执行完是通过animateBasedOnTime来完成的,下面看其中的原理:
//该方法根据currentTime计算流逝的时间以及流逝百分比,从而计算出动画是否结束,其中包括重复次数。
//这里注意 currentTime为毫秒,其实在FrameCallback.doFrame(long frameTimeNanos)中返回的是纳秒,我们的AnimationHandler中取的是 public long getFrameTime() {
return getFrameTimeNanos() / TimeUtils.NANOS_PER_MS;
}该方法返回的毫秒。
boolean animateBasedOnTime(long currentTime) {
boolean done = false;
if (mRunning) {
//计算总时长缩放比,默认无缩放,即setDuration(long duration)中设置的毫秒总时长
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);
if (scaledDuration == 0) {
// 0 duration animator, ignore the repeat count and skip to the end
done = true;
} else if (newIteration && !lastIterationFinished) {
// 重复监听回调
if (mListeners != null) {
int numListeners = mListeners.size();
for (int i = 0; i < numListeners; ++i) {
mListeners.get(i).onAnimationRepeat(this);
}
}
} else if (lastIterationFinished) {
done = true;
}
//计算总体比例,包括重复次数
mOverallFraction = clampFraction(fraction);
//得到当前比例
float currentIterationFraction = getCurrentIterationFraction(
mOverallFraction, mReversing);
animateValue(currentIterationFraction);
}
return done;
}
这个方法的大部分代码都是计算流逝时间占总执行时间的比例,其中包括重复次数、是否倒序播放等,得到该值后,接下来就需要就需要计算我们动画的值的变化,比如ofInt(0,100)方法,就需要流逝时间的百分比以及时间插值器的规则来计算到目标值是如何从0-100的变化过程。解析分析animateValue的实现过程:
@CallSuper
@UnsupportedAppUsage
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);
}
}
}
2.3.2.2 根据(TimeInterpolator)时间插值规则计算时间流逝比例
在animateValue的方法中,第一个计算就是根据我们设置的setInterpolator(TimeInterpolator value)来重新计算百分比的变化,这里我们先看一个简单的LinearInterpolator的实现
public class LinearInterpolator extends BaseInterpolator implements NativeInterpolator {
public LinearInterpolator() {
}
public LinearInterpolator(Context context, AttributeSet attrs) {
}
//直接返回我们时间流逝的百分比
public float getInterpolation(float input) {
return input;
}
/** @hide */
@Override
public long createNativeInterpolator() {
return NativeInterpolatorFactory.createLinearInterpolator();
}
}
LinearInterpolator是一个变化率恒定不变的插值器,屏幕的刷新机制是16ms刷新一次,因此我们在animateBasedOnTime中计算的结果是一个变化率恒定不变的,在使用中表现出来的结果就是一个运算运动。我在使用ValueAnimator的时候如果不设置时间插值器,系统默认使用的是AccelerateDecelerateInterpolator,下面在看一下它的实现原理:
系统默认插值器:
private TimeInterpolator mInterpolator = sDefaultInterpolator;
// The time interpolator to be used if none is set on the animation
private static final TimeInterpolator sDefaultInterpolator =
new AccelerateDecelerateInterpolator();
public class AccelerateDecelerateInterpolator extends BaseInterpolator
implements NativeInterpolator {
public AccelerateDecelerateInterpolator() {
}
@SuppressWarnings({"UnusedDeclaration"})
public AccelerateDecelerateInterpolator(Context context, AttributeSet attrs) {
}
//计算变化率
public float getInterpolation(float input) {
return (float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
}
/** @hide */
@Override
public long createNativeInterpolator() {
return NativeInterpolatorFactory.createAccelerateDecelerateInterpolator();
}
}
AccelerateDecelerateInterpolator插值器的变化率在开始和结束时缓慢但在中间会加快。这里使用的数学里面的计算原理,不在具体分析。目前系统提供以下时间插值器的实现类:
- AccelerateDecelerateInterpolator:该插值器的变化率在开始和结束时缓慢但在中间会加快。
- AccelerateInterpolator:该插值器的变化率在开始时较为缓慢,然后会加快。
- AnticipateInterpolator:该插值器先反向变化,然后再急速正向变化。
- AnticipateOvershootInterpolator:该插值器先反向变化,再急速正向变化,然后超过定位值,最后返回到最终值
- BounceInterpolator:该插值器的变化会跳过结尾处。
- CycleInterpolator:该插值器的动画会在指定数量的周期内重复。
- DecelerateInterpolator:该插值器的变化率开始很快,然后减速。
- LinearInterpolator:该插值器的变化率恒定不变。
- OvershootInterpolator:该插值器会急速正向变化,再超出最终值,然后返回。
如果上述的这些时间插值器不满足我们的业务开发需求,那么根据TimeInterpolator来实现自己的处理逻辑。
根据时间插值器计算出比例后,那么那么接下来就要改变对应的值,我们在开发中经常在onAnimationUpdate()回调中通过animator.getAnimatedValue()取出我们设定的目标值的变化。下面分析其中的实现过程:
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);
}
.......
}
mValues是一个 PropertyValuesHolder[]数组,是我们在调用ofInt()、ofFloat()等方法的时候初始化的。下面进入calculateValue方法:
void calculateValue(float fraction) {
Object value = mKeyframes.getValue(fraction);
mAnimatedValue = mConverter == null ? value : mConverter.convert(value);
}
上面的代码中调用了keyframes中的方法来计算当前的变化值
public interface Keyframes extends Cloneable {
......
Object getValue(float fraction);
......
}
Keyframes是一个抽象类,具体的实现由子类完成,下面已ofInt(0,100)为例来分析计算过程。调用ofInt(0,100)后,会执行到下面的代码,创建一个keyframeSet:
public static KeyframeSet ofInt(int... values) {
int numKeyframes = values.length;
IntKeyframe keyframes[] = new IntKeyframe[Math.max(numKeyframes,2)];
if (numKeyframes == 1) {
keyframes[0] = (IntKeyframe) Keyframe.ofInt(0f);
keyframes[1] = (IntKeyframe) Keyframe.ofInt(1f, values[0]);
} else {
keyframes[0] = (IntKeyframe) Keyframe.ofInt(0f, values[0]);
for (int i = 1; i < numKeyframes; ++i) {
keyframes[i] =
(IntKeyframe) Keyframe.ofInt((float) i / (numKeyframes - 1), values[i]);
}
}
return new IntKeyframeSet(keyframes);
}
这里将相关可变参数values的值取出,并创建对应IntKeyframe的来存储value值。接下来进入getValue()的计算过程:
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());
}
if (fraction <= 0f) {
final Keyframe nextKeyframe = mKeyframes.get(1);
final TimeInterpolator interpolator = nextKeyframe.getInterpolator();
if (interpolator != null) {
fraction = interpolator.getInterpolation(fraction);
}
final float prevFraction = mFirstKeyframe.getFraction();
float intervalFraction = (fraction - prevFraction) /
(nextKeyframe.getFraction() - prevFraction);
return mEvaluator.evaluate(intervalFraction, mFirstKeyframe.getValue(),
nextKeyframe.getValue());
} else if (fraction >= 1f) {
final Keyframe prevKeyframe = mKeyframes.get(mNumKeyframes - 2);
final TimeInterpolator interpolator = mLastKeyframe.getInterpolator();
if (interpolator != null) {
fraction = interpolator.getInterpolation(fraction);
}
final float prevFraction = prevKeyframe.getFraction();
float intervalFraction = (fraction - prevFraction) /
(mLastKeyframe.getFraction() - prevFraction);
return mEvaluator.evaluate(intervalFraction, prevKeyframe.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();
}
这里我传入两个值(0,100)因此会直接进入下面的代码执行:
if (mNumKeyframes == 2) {
if (mInterpolator != null) {
fraction = mInterpolator.getInterpolation(fraction);
}
return mEvaluator.evaluate(fraction, mFirstKeyframe.getValue(),
mLastKeyframe.getValue());
}
在创建KeyFrameSet的时候,并没有传入TimeInterpolator,因此不会进入差值器的计算规则,返回的值是通过TypeEvaluator评估程序进行计算的,那么KeyframeSet的TypeEvaluator 是在哪里进行的初始化的呢? 其实在ValueAnimator的start()方法中,会执行:
void initAnimation() {
if (!mInitialized) {
int numValues = mValues.length;
for (int i = 0; i < numValues; ++i) {
mValues[i].init();
}
mInitialized = true;
}
}
mValues[i].init()方法对应的是PropertyValuesHolde的init()方法:
void init() {
if (mEvaluator == null) {
// We already handle int and float automatically, but not their Object
// equivalents
mEvaluator = (mValueType == Integer.class) ? sIntEvaluator :
(mValueType == Float.class) ? sFloatEvaluator :
null;
}
if (mEvaluator != null) {
// KeyframeSet knows how to evaluate the common types - only give it a custom
// evaluator if one has been set on this class
mKeyframes.setEvaluator(mEvaluator);
}
}
2.3.2.3 根据TypeEvaluator评估程序计算值的变化
在这里我们调用的是ofInt()方法,因此会使用IntEvaluator,下面查看IntEvaluator的代码:
public class IntEvaluator implements TypeEvaluator<Integer> {
//根据时间产值计算的时间流逝百分比来计算我们的animateValue值的变化过程
public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
int startInt = startValue;
return (int)(startInt + fraction * (endValue - startInt));
}
}
我们的getValue传入的是我ofInt(0,100)的startValue = 0和endValue = 100;
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());
}
......
return mLastKeyframe.getValue();
}
目前系统提供了一下评估程序的实现:
- IntEvaluator :这是用于计算 int 属性的值的默认评估程序。
- FloatEvaluator:这是用于计算 float 属性的值的默认评估程序。
- ArgbEvaluator:这是用于计算颜色属性的值(用十六进制值表示)的默认评估程序。
如果上述的实现不满足我们的开发要求,则需要根据实现TypeEvaluator来自定义评估程序。
到了这里,整个ValueAnimator的原理已经分析完成,最后我们总结一下ValueAnimator的整体流程
2.3.2.4 ValueAnimator流程总结
- ValueAnimator的时间流逝机制是根据屏幕的刷新机制来实现的,主要使用Choreographer的相关方法
- 使用TimeInterpolator时间插值器来动态改变当前流逝时间的比例值
- 使用TypeEvaluator评估程序来计算我们属性值的变化
2.3.4 了解ObjectAnimator工作原理
ObjectAnimator是ValueAnimator的子类,相关的动画原理和ValueAnimator一致,区别在于可以设置一个视图以及对应的属性,在程序运行过程中自动改变对应的属性值。接下通过分析ofInt()来了解其执行流程。
public static ObjectAnimator ofInt(Object target, String propertyName, int... values) {
ObjectAnimator anim = new ObjectAnimator(target, propertyName);
anim.setIntValues(values);
return anim;
}
这个方法和ValueAnimator的public static ValueAnimator ofInt(int… values) 方法对比,多了两个参数,分别是target和propertyName。这里的target没有指定具体类型,我们在时间开发中经常传入的是View对象。propertyName是改对象属性的名字,需要有set方法。比如propertyName传入name,那么对于的target中需要有对应的setName()方法,这里动画属性属性的变化才作用到应到target中。接下里实例化了一个ObjectAnimaotr对象:
private ObjectAnimator(Object target, String propertyName) {
setTarget(target);
setPropertyName(propertyName);
}
@Override
public void setTarget(@Nullable Object target) {
final Object oldTarget = getTarget();
if (oldTarget != target) {
if (isStarted()) {
cancel();
}
mTarget = target == null ? null : new WeakReference<Object>(target);
// New target should cause re-initialization prior to starting
mInitialized = false;
}
}
public void setPropertyName(@NonNull String propertyName) {
// mValues could be null if this is being constructed piecemeal. Just record the
// propertyName to be used later when setValues() is called if so.
if (mValues != null) {
PropertyValuesHolder valuesHolder = mValues[0];
String oldName = valuesHolder.getPropertyName();
valuesHolder.setPropertyName(propertyName);
mValuesMap.remove(oldName);
mValuesMap.put(propertyName, valuesHolder);
}
mPropertyName = propertyName;
// New property/values/target should cause re-initialization prior to starting
mInitialized = false;
}
这些代码将target和propertyName保存保存起来。初始化工作完成后,剩下就是开始动画:
@Override
public void start() {
AnimationHandler.getInstance().autoCancelBasedOn(this);
super.start();
}
这个start()方法基本是调用super.start()方法。在前面分析ValueAnimator的流程中,调用start()方法后,如果没有初始化完成,会进行一些初始化工作,下面分析initAnimation()方法:
@CallSuper
@Override
void initAnimation() {
if (!mInitialized) {
// mValueType may change due to setter/getter setup; do this before calling super.init(),
// which uses mValueType to set up the default type evaluator.
final Object target = getTarget();
if (target != null) {
final int numValues = mValues.length;
for (int i = 0; i < numValues; ++i) {
mValues[i].setupSetterAndGetter(target);
}
}
super.initAnimation();
}
}
这个方法里面有个非常重要的操作,就是完成对传入的propertyName对于Method的创建。下面进入PropertyValuesHolder的
//
void setupSetterAndGetter(Object target) {
.....
if (mProperty == null) {
Class targetClass = target.getClass();
if (mSetter == null) {
setupSetter(targetClass);
}
.....
}
......
}
void setupSetter(Class targetClass) {
Class<?> propertyType = mConverter == null ? mValueType : mConverter.getTargetType();
mSetter = setupSetterOrGetter(targetClass, sSetterPropertyMap, "set", propertyType);
}
private Method setupSetterOrGetter(Class targetClass,
HashMap<Class, HashMap<String, Method>> propertyMapMap,
String prefix, Class valueType) {
Method setterOrGetter = null;
synchronized(propertyMapMap) {
......
if (!wasInMap) {
setterOrGetter = getPropertyFunction(targetClass, prefix, valueType);
if (propertyMap == null) {
propertyMap = new HashMap<String, Method>();
propertyMapMap.put(targetClass, propertyMap);
}
propertyMap.put(mPropertyName, setterOrGetter);
}
}
return setterOrGetter;
}
//根据名字创建method
private Method getPropertyFunction(Class targetClass, String prefix, Class valueType) {
// TODO: faster implementation...
Method returnVal = null;
String methodName = getMethodName(prefix, mPropertyName);
Class args[] = null;
if (valueType == null) {
try {
returnVal = targetClass.getMethod(methodName, args);
} catch (NoSuchMethodException e) {
// Swallow the error, log it later
}
} else {
args = new Class[1];
Class typeVariants[];
//匹配对于的参数
if (valueType.equals(Float.class)) {
typeVariants = FLOAT_VARIANTS;
} else if (valueType.equals(Integer.class)) {
typeVariants = INTEGER_VARIANTS;
} else if (valueType.equals(Double.class)) {
typeVariants = DOUBLE_VARIANTS;
} else {
typeVariants = new Class[1];
typeVariants[0] = valueType;
}
for (Class typeVariant : typeVariants) {
args[0] = typeVariant;
try {
returnVal = targetClass.getMethod(methodName, args);
if (mConverter == null) {
// change the value type to suit
mValueType = typeVariant;
}
return returnVal;
} catch (NoSuchMethodException e) {
// Swallow the error and keep trying other variants
}
}
// If we got here, then no appropriate function was found
}
return returnVal;
}
//根据前缀和属性,获取方法名
static String getMethodName(String prefix, String propertyName) {
if (propertyName == null || propertyName.length() == 0) {
// shouldn't get here
return prefix;
}
//自动将属性的第一个字母转化成小写
char firstLetter = Character.toUpperCase(propertyName.charAt(0));
String theRest = propertyName.substring(1);
return prefix + firstLetter + theRest;
}
经过上面的操作后,自动给我们生成了一个setXXX和getXXX的Method,那么这个Mehtod在什么时候调用呢? 在刷新回调中会执行doFrame(),同时会执行animateValue()方法进行属性值变化的计算,下面查看ObjectAnimator中该方法的逻辑:
@CallSuper
@Override
void animateValue(float fraction) {
final Object target = getTarget();
if (mTarget != null && target == null) {
// We lost the target reference, cancel and clean up. Note: we allow null target if the
/// target has never been set.
cancel();
return;
}
//调用父方法完成属性值变换计算
super.animateValue(fraction);
int numValues = mValues.length;
for (int i = 0; i < numValues; ++i) {
//设置属性值
mValues[i].setAnimatedValue(target);
}
}
上述的方法中调用PropertyValuesHolder.setAnimatedValue(Object target),这个方法其实就是属性值得以改变的地方。
void setAnimatedValue(Object target) {
if (mProperty != null) {
mProperty.set(target, getAnimatedValue());
}
if (mSetter != null) {
try {
mTmpValueArray[0] = getAnimatedValue();
//反射执行方法
mSetter.invoke(target, mTmpValueArray);
} catch (InvocationTargetException e) {
Log.e("PropertyValuesHolder", e.toString());
} catch (IllegalAccessException e) {
Log.e("PropertyValuesHolder", e.toString());
}
}
}
setAnimatedValue()方法将我们先前初始化的mSettter反射调用,从而执行Object对应方法自身的逻辑。
到了这里ObjectAnimator的执行流程基本分析完毕,对比Animator有已下特点:
- 支持Object 和propertyName
- 在动画初始化的过程中会初始propertyName对应的get和set Method,只支持一个参数
- 在属性值改变的过程中,会反射调用propertyName对应的setter方法
- ObjectAnimator对propertyName没有限制,只需要我们的targetObject有对应get和set的实现即可
三、总结
整个属性动画的原理基本分析完成,了解清楚ValueAniamtor原理后,对应的ObjectAnimator理解起来就容易的多,分析完成整个原理后,总结出属性动画具有以下特点:
- ValueAnimator的时间流逝机制是根据屏幕的刷新机制来实现的,主要使用Choreographer的相关方法
- 使用TimeInterpolator时间插值器来动态改变当前流逝时间的比例值
- 使用TypeEvaluator评估程序来计算我们属性值的变化
- ObjectAnimator对propertyName没有限制,只需要我们的targetObject有对应get和set的实现即可
- ObjectAnimato对propertyName的执行是通过反射来完成的。
1267



被折叠的 条评论
为什么被折叠?



