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

Android 動畫透視:插值器與估值器源碼全解

編輯:關於 Android 程式設計

想真正吃透 Android 動畫,光會調 API 是不夠的,得潛到源碼裡去看它是怎麼算的。本文延續前面的入門內容,從實現層面拆解動畫背後的兩位主角——插值器(Interpolator)與估值器(Evaluator)。

一、插值器:把時間「掰彎」的函數

時間插值器本質上就是一個映射關係 y = f(t),這裡的 t 並不是真實秒數,而是 elapsed time / duration 得出的歸一化比例,落在 0 到 1 之間。系統自帶的每一個插值器都繼承自 BaseInterpolator,內部結構高度相似。下面用 AccelerateInterpolator 當樣本:

public class AccelerateInterpolator extends BaseInterpolator implements NativeInterpolatorFactory {
    private final float mFactor;
    private final double mDoubleFactor;

    // 無參構造,factor 預設為 1
    public AccelerateInterpolator() {
        mFactor = 1.0f;
        mDoubleFactor = 2.0;
    }

    public AccelerateInterpolator(float factor) {
        mFactor = factor;
        mDoubleFactor = 2 * mFactor;
    }

    public AccelerateInterpolator(Context context, AttributeSet attrs) {
        this(context.getResources(), context.getTheme(), attrs);
    }

    /** @hide 真正解析資源檔案的構造 */
    public AccelerateInterpolator(Resources res, Theme theme, AttributeSet attrs) {
        TypedArray a;
        if (theme != null) {
            a = theme.obtainStyledAttributes(attrs, R.styleable.AccelerateInterpolator, 0, 0);
        } else {
            a = res.obtainAttributes(attrs, R.styleable.AccelerateInterpolator);
        }
        // 資源裡沒寫 factor 時,預設 1.0f
        mFactor = a.getFloat(R.styleable.AccelerateInterpolator_factor, 1.0f);
        mDoubleFactor = 2 * mFactor;
        setChangingConfiguration(a.getChangingConfigurations());
        a.recycle(); // 用完記得回收
    }

    // 插值的核心:定義輸入與輸出的映射
    public float getInterpolation(float input) {
        if (mFactor == 1.0f) {
            return input * input;
        } else {
            return (float) Math.pow(input, mDoubleFactor);
        }
    }

    /** @hide */
    @Override
    public long createNativeInterpolator() {
        return NativeInterpolatorFactoryHelper.createAccelerateInterpolator(mFactor);
    }
}

三層繼承關係其實很單薄:BaseInterpolator 實現了 Interpolator,而 Interpolator 自己什麼都沒定義,只是乾脆地繼承了 TimeInterpolator。

abstract public class BaseInterpolator implements Interpolator {
    private int mChangingConfiguration;

    /** @hide */
    public int getChangingConfiguration() {
        return mChangingConfiguration;
    }

    /** @hide */
    void setChangingConfiguration(int changingConfiguration) {
        mChangingConfiguration = changingConfiguration;
    }
}

真正訂下規則的是 TimeInterpolator,全體插值器的靈魂方法就在這裡:

public interface TimeInterpolator {
    /*
     * @param input 動畫已執行的時間比例,∈[0,1]
     * @return 插值換算後的值
     */
    float getInterpolation(float input);
}

二、九種內建插值器的公式與曲線

1. LinearInterpolator(線性)

  • 資源 ID:@android:anim/linear_interpolator
  • 構造:public LinearInterpolator(),無任何可調參數
  • 公式:y = t
  • 曲線:

2. AccelerateInterpolator(加速)

  • 資源 ID:@android:anim/accelerate_interpolator
  • 構造:()(factor 預設 1)、(float factor)、(Context, AttributeSet)
  • 公式:y = t^(2f),f 為加速因子,預設 1;缺省即 y = t^2
  • 曲線:

3. DecelerateInterpolator(減速)

  • 資源 ID:@android:anim/decelerate_interpolator
  • 構造:同上三種,可從資源檔讀取 factor
  • 公式:y = 1 - (1 - t)^(2f);缺省為 y = 2t - t^2
  • 曲線:

4. AccelerateDecelerateInterpolator(先加速後減速)

  • 資源 ID:@android:anim/accelerate_decelerate_interpolator
  • 構造:public AccelerateDecelerateInterpolator(),沒有可調參數
  • 公式:y = 0.5cos((t+1)π) + 0.5
  • 曲線:

5. AnticipateInterpolator(先回拉再衝出)

  • 資源 ID:@android:anim/anticipate_interpolator
  • 構造:()(tension 預設 2)、(float tension)、(Context, AttributeSet)
  • 公式:y = t*t*((s+1)t - s);缺省為 y = t*t*(3t-2)
  • 曲線:

6. OvershootInterpolator(衝過頭再回來)

  • 資源 ID:@android:anim/overshoot_interpolator
  • 構造:()(tension 預設 2)、(float tension)、(Context, AttributeSet)
  • 公式:y = (t-1)(t-1)((s+1)(t-1) + s) + 1;缺省為 y = (t-1)(t-1)(3t-1) + 1
  • 曲線:

7. AnticipateOvershootInterpolator(回拉 + 衝過頭)

  • 資源 ID:@android:anim/anticipate_overshoot_interpolator
  • 構造:()(tension 預設 3)、(float tension)(內部乘以 1.5)、(float tension, float extraTension)、(Context, AttributeSet)
  • 公式:
    • t < 0.5:y = 2t*t*(2t*s + 2t - s),缺省 y = 2t*t*(8t-3)
    • t ≥ 0.5:y = 2(t-1)(t-1)(2(s+1)(t-1) + s) + 1,缺省 y = 2(t-1)(t-1)(8t-5) + 1
  • 曲線:

8. BounceInterpolator(彈跳)

  • 資源 ID:@android:anim/bounce_interpolator
  • 構造:public BounceInterpolator(),無參數
  • 公式(分段):
    • t < 0.3535:y = 8*(1.1226t)^2
    • t < 0.7408:y = 8*(1.1226t - 0.54719)^2 + 0.7
    • t < 0.9644:y = 8*(1.1226t - 0.8526)^2 + 0.9
    • t ≤ 1.0:y = 8*(1.1226t - 1.0435)^2 + 0.95
  • 曲線:

9. CycleInterpolator(循環震盪)

  • 資源 ID:@android:anim/cycle_interpolator
  • 構造:(float cycles)、(Context, AttributeSet)(cycles 預設 1)
  • 公式:y = sin(2*c*t*π);缺省為 y = sin(2*t*π)
  • 曲線:

三、估值器:把比例換成真正的屬性值

插值器算完的只是一個 0 到 1 之間的比例,把它變成具體的透明度、座標或顏色,是估值器的活儿。所有估值器都實現了帶泛型的 TypeEvaluator,自訂時只要照著實作一個方法就好:

public interface TypeEvaluator<T> {
    /*
     * @param fraction 插值器換算後的值
     * @param startValue 屬性起始值
     * @param endValue 屬性結束值
     * @return 換算後的值
     */
    public T evaluate(float fraction, T startValue, T endValue);
}

IntEvaluator

處理 Integer 型屬性,結果與 fraction 呈一次函數關係。

public class IntEvaluator implements TypeEvaluator<Integer> {
    // result = x0 + t * (x1 - x0)
    public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
        int startInt = startValue;
        return (int) (startInt + fraction * (endValue - startInt));
    }
}

FloatEvaluator

public class FloatEvaluator implements TypeEvaluator<Number> {
    public Float evaluate(float fraction, Number startValue, Number endValue) {
        float startFloat = startValue.floatValue();
        return startFloat + fraction * (endValue.floatValue() - startFloat);
    }
}

ArgbEvaluator

顏色動畫的關鍵:把 ARGB 四個通道拆開,各自線性插值後再拼回去。

public class ArgbEvaluator implements TypeEvaluator {
    private static final ArgbEvaluator sInstance = new ArgbEvaluator();

    /** @hide 註:構造方法並未宣告為 private,因此這個單例對上層開發者其實不可見 */
    public static ArgbEvaluator getInstance() {
        return sInstance;
    }

    public Object evaluate(float fraction, Object startValue, Object endValue) {
        int startInt = (Integer) startValue;
        int startA = (startInt >> 24) & 0xff;
        int startR = (startInt >> 16) & 0xff;
        int startG = (startInt >> 8) & 0xff;
        int startB = startInt & 0xff;

        int endInt = (Integer) endValue;
        int endA = (endInt >> 24) & 0xff;
        int endR = (endInt >> 16) & 0xff;
        int endG = (endInt >> 8) & 0xff;
        int endB = endInt & 0xff;

        return (int) ((startA + (int)(fraction * (endA - startA))) << 24)
             | (int) ((startR + (int)(fraction * (endR - startR))) << 16)
             | (int) ((startG + (int)(fraction * (endG - startG))) << 8)
             | (int) (startB + (int)(fraction * (endB - startB)));
    }
}

四、小結

插值器決定「動得快慢」,估值器決定「值是多少」,兩者串起來才是完整的屬性動畫。 nine 種內建插值器的差異,本質就是九條不同的 y = f(t) 曲線;三個內建估值器的實作則相當樸素,幾乎都是線性內插。

最容易踩的坑只有一個:傳進 evaluate() 的 fraction 已經是插值器加工過的比例,而不是原始的 elapsed time。搞錯這一點,自訂插值器就會完全失效。

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