Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 屬性動畫源碼解析:從 ofInt 到 start 的完整鏈路

編輯:關於 Android 程式設計

一、出發前的猜想

想做炫酷的動畫,屬性動畫往往是首選。關於用法已有不少文章講得很透,這裡不再重複,重點是往下挖一層,看看它內部究竟怎麼跑。

分析源碼前先立個靶子。最常用的入口是 ObjectAnimator,只要指定目標 View、屬性名、目標值,再 start(),動畫就跑起來了:

ObjectAnimator
    .ofInt(target, propName, values[])
    .setInterpolator(new LinearInterpolator())
    .setEvaluator(new IntEvaluator())
    .setDuration(500)
    .start();

逐行來看:設置作用的 View 與屬性,給出開始值、結束值和中間任意個關鍵值;接著設置插值器(Interpolator,如 LinearInterpolator、AccelerateInterpolator);再設置估值算法(Evaluator),聽起來高端,實現其實一行:

return (int)(startInt + fraction * (endValue - startInt));

也就是「起始值 + 當前進度百分比 ×(結束值 − 起始值)」。而這個 fraction 正是插值器算出來的,線性插值器下它就是 (currentTime - mStartTime) / mDuration,即動畫已執行時間佔總時長的比例。

那麼,如果讓你自己設計一套屬性動畫框架,你會怎麼做?大概思路是:在 start() 裡啟動一個計時任務,每幀根據 Interpolator 算出 fraction,交給 Evaluator 得到當前應設定的值,再反射寫回 target 的指定屬性。源碼的實現自然複雜得多,但主幹離不開這個模型。接下來就是去驗證這個猜測。

二、ofInt:把參數收攏起來

為簡化說明,這裡假設 values 只有一個元素。

public static ObjectAnimator ofInt(Object target, String propertyName, int... values) {
    ObjectAnimator anim = new ObjectAnimator(target, propertyName);
    anim.setIntValues(values);
    return anim;
}

private ObjectAnimator(Object target, String propertyName) {
    mTarget = target;
    setPropertyName(propertyName);
}

@Override
public void setIntValues(int... values) {
    setValues(PropertyValuesHolder.ofInt(mPropertyName, values));
}

構造方法只是記下 target 和 propertyName,接著把兩者轉交給 PropertyValuesHolder。從字面理解,這個類保存的是「動畫期間」該屬性的一組值。

public static PropertyValuesHolder ofInt(String propertyName, int... values) {
    return new IntPropertyValuesHolder(propertyName, values);
}

@Override
public void setIntValues(int... values) {
    mValueType = int.class;
    mKeyframeSet = KeyframeSet.ofInt(values);
    mIntKeyframeSet = (IntKeyframeSet) mKeyframeSet;
}

於是裡面存了 propertyName、valueType,還有一個新面孔 mKeyframeSet。Keyframe 叫關鍵幀,保存 time/value 對;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 {
        // 省略
    }
    return new IntKeyframeSet(keyframes);
}

public IntKeyframeSet(IntKeyframe... keyframes) {
    mNumKeyframes = keyframes.length;
    mKeyframes = new ArrayList<Keyframe>();
    mKeyframes.addAll(Arrays.asList(keyframes));
    mFirstKeyframe = mKeyframes.get(0);
    mLastKeyframe = mKeyframes.get(mNumKeyframes - 1);
    mInterpolator = mLastKeyframe.getInterpolator();
}

注意這裡的細節:即使只給一個目標值,內部也會補成兩幀——fraction 0 處無值,fraction 1 處放目標值。Keyframe 本身存的很簡單:

IntKeyframe(float fraction, int value) {
    mFraction = fraction;
    mValue = value;
    mValueType = int.class;
    mHasValue = true;
}

最後交回 ObjectAnimator 的 setValues:

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);
    }
    // 新的屬性/值/目標需要重新初始化
    mInitialized = false;
}

小結一下 ofInt:它記錄了 target、propName、values(被輾轉包裝成 PropertyValuesHolder),並建立一個 key 為屬性名、value 為 PropertyValuesHolder 的 mValuesMap。

三、setInterpolator 與 setEvaluator

@Override
public void setInterpolator(TimeInterpolator value) {
    if (value != null) {
        mInterpolator = value;
    } else {
        mInterpolator = new LinearInterpolator();   // 默認線性
    }
}

public void setEvaluator(TypeEvaluator value) {
    if (value != null && mValues != null && mValues.length > 0) {
        mValues[0].setEvaluator(value);
    }
}

// PropertyValuesHolder 內部
public void setEvaluator(TypeEvaluator evaluator) {
    mEvaluator = evaluator;
    mKeyframeSet.setEvaluator(evaluator);
}

可以看出,估值算法最終被同時交給了 PropertyValuesHolder 和 KeyframeSet。

四、setDuration

private long mDuration = (long)(300 * sDurationScale);
private long mUnscaledDuration = 300;
private static float sDurationScale = 1.0f;

public ObjectAnimator setDuration(long duration) {
    if (duration < 0) {
        throw new IllegalArgumentException("Animators cannot have negative duration: " + duration);
    }
    mUnscaledDuration = duration;
    mDuration = (long)(duration * sDurationScale);
    return this;
}

就是記下時長。那個 sDurationScale 默認為 1,可以理解為調速倍率——調成 10,動畫就會放慢十倍播放,方便調試。

五、start:真正干活的地方

// ObjectAnimator
@Override
public void start() {
    super.start();
}

// ValueAnimator
@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");
    }
    mPlayingBackwards = playBackwards;
    mCurrentIteration = 0;
    mPlayingState = STOPPED;
    mStarted = true;
    mStartedDelay = false;
    mPaused = false;
    AnimationHandler animationHandler = getOrCreateAnimationHandler();
    animationHandler.mPendingAnimations.add(this);
    if (mStartDelay == 0) {
        // 在真正開始運行前,先設置動畫的初始值
        setCurrentPlayTime(0);
        mPlayingState = STOPPED;
        mRunning = true;
        notifyStartListeners();
    }
    animationHandler.start();
}

幾個標志位的含義:mPlayingBackwards 表示是否反向播放;mCurrentIteration 記錄已執行次數(與 setRepeatCount 相關);mPlayingState 標示動畫狀態。AnimationHandler 存在於當前線程的 ThreadLocal 中,內部用若干 List 存放不同狀態的動畫;這裡先把自己塞進 mPendingAnimations。若未設置 startDelay(默認 0),則立即調用 setCurrentPlayTime(0) 初始化,並回調 onAnimationStart。

public void setCurrentPlayTime(long playTime) {
    initAnimation();
    long currentTime = AnimationUtils.currentAnimationTimeMillis();
    if (mPlayingState != RUNNING) {
        mSeekTime = playTime;
        mPlayingState = SEEKED;
    }
    mStartTime = currentTime - playTime;
    doAnimationFrame(currentTime);
}

void initAnimation() {
    if (!mInitialized) {
        int numValues = mValues.length;
        for (int i = 0; i < numValues; ++i) {
            mValues[i].init();
        }
        mInitialized = true;
    }
}

PropertyValuesHolder.init() 會在沒有外部指定估值器時,根據 valueType 自動挑一個:Integer 用 sIntEvaluator,Float 用 sFloatEvaluator。

final boolean doAnimationFrame(long frameTime) {
    final long currentTime = Math.max(frameTime, mStartTime);
    return animationFrame(currentTime);
}

boolean animationFrame(long currentTime) {
    boolean done = false;
    switch (mPlayingState) {
        case RUNNING:
        case SEEKED:
            float fraction = mDuration > 0 ? (float)(currentTime - mStartTime) / mDuration : 1f;
            if (fraction >= 1f) {
                // 動畫結束處理
            }
            if (mPlayingBackwards) {
                fraction = 1f - fraction;
            }
            animateValue(fraction);
            break;
    }
    return done;
}

fraction 的計算正是我們猜想的那個式子:已執行時間除以總時長。

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);
        }
    }
    for (int i = 0; i < numValues; ++i) {
        mValues[i].setAnimatedValue(mTarget);            // 反射寫回
    }
}

// PropertyValuesHolder
void calculateValue(float fraction) {
    mAnimatedValue = mKeyframeSet.getValue(fraction);
}

// IntKeyframeSet
public int getIntValue(float fraction) {
    if (mNumKeyframes == 2) {
        if (firstTime) {
            firstTime = false;
            firstValue = ((IntKeyframe) mKeyframes.get(0)).getIntValue();
            lastValue = ((IntKeyframe) mKeyframes.get(1)).getIntValue();
            deltaValue = lastValue - firstValue;
        }
        if (mInterpolator != null) {
            fraction = mInterpolator.getInterpolation(fraction);
        }
        if (mEvaluator == null) {
            return firstValue + (int)(fraction * deltaValue);
        } else {
            return ((Number) mEvaluator.evaluate(fraction, firstValue, lastValue)).intValue();
        }
    }
    // 省略
}

可以看到,mEvaluator 為 null 時走的正是 firstValue + fraction * deltaValue,與 IntEvaluator 的默認實現一致。算出來的值最終存進 mAnimatedValue,再由 setAnimatedValue 反射寫入 target 的屬性——target 從構造時就存著,propName 也早已記錄,值剛剛算好,三要素齊全。

六、每幀重複是怎麼做到的

回到 start() 的最後一行:

public void start() {
    scheduleAnimation();
}

private void scheduleAnimation() {
    if (!mAnimationScheduled) {
        mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
        mAnimationScheduled = true;
    }
}

public void run() {
    mAnimationScheduled = false;
    doAnimationFrame(mChoreographer.getFrameTime());
}

private void doAnimationFrame(long frameTime) {
    while (mPendingAnimations.size() > 0) {
        ArrayList<ValueAnimator> pendingCopy = (ArrayList<ValueAnimator>) mPendingAnimations.clone();
        mPendingAnimations.clear();
        int count = pendingCopy.size();
        for (int i = 0; i < count; ++i) {
            ValueAnimator anim = pendingCopy.get(i);
            if (anim.mStartDelay == 0) {
                anim.startAnimation(this);   // 內部主要是 handler.mAnimations.add(this)
            } else {
                mDelayedAnims.add(anim);
            }
        }
    }
    // 處理所有活動中的動畫
    int numAnims = mAnimations.size();
    for (int i = 0; i < numAnims; ++i) {
        mTmpAnimations.add(mAnimations.get(i));
    }
    for (int i = 0; i < numAnims; ++i) {
        ValueAnimator anim = mTmpAnimations.get(i);
        if (mAnimations.contains(anim) && anim.doAnimationFrame(frameTime)) {
            mEndingAnims.add(anim);
        }
    }
    mTmpAnimations.clear();
    if (mEndingAnims.size() > 0) {
        for (int i = 0; i < mEndingAnims.size(); ++i) {
            mEndingAnims.get(i).endAnimation(this);
        }
        mEndingAnims.clear();
    }
    // 若還有活動或延遲中的動畫,安排下一幀
    if (!mAnimations.isEmpty() || !mDelayedAnims.isEmpty()) {
        scheduleAnimation();
    }
}

關鍵就在最後那個 if:只要動畫還沒結束,就再次調用 scheduleAnimation(),而 scheduleAnimation 內部通過 mChoreographer 把自己作為 Runnable 重新投遞,於是 run() 又會被執行一次,形成逐幀循環。animationFrame() 在 fraction ≥ 1 時回傳 true,動畫被移入 mEndingAnims,endAnimation() 中會從 mAnimations 移除並回調 onAnimationEnd,同時重置各標志位,循環自然終止。

七、總結

配置階段:ofInt 實例化 ObjectAnimator 並記錄 target、propName 與 values(包裝為 PropertyValuesHolder,內部含 propName、valueType、keyframeSet);setInterpolator 存插值器,setDuration 存時長,setEvaluator 把估值算法交給 PropertyValuesHolder 與 KeyframeSet。KeyframeSet 內存 Keyframe 集合,每個 Keyframe 存 fraction、valueType、value、hasValue。

運行階段(start):先更新狀態並算出初始 fraction =(currentTime − mStartTime)/ mDuration;交給插值器得到新的 fraction;再交給估值算法,結合起始值、結束值算出當前應設定的值;最後反射寫入目標屬性。若動畫未結束,則透過 scheduleAnimation() 借助 mChoreographer 一幀一幀重複上述過程。

最後提醒一個看源碼的實用技巧:你點進去的方法未必是運行時真正被調用的那個。比如追 ObjectAnimator 的方法時可能落到父類 ValueAnimator 裡,記得確認子類是否重寫過——若重寫了,該看的是子類版本。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved