Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

8.4.4 屬性動畫進階:Evaluator、Interpolator 與 ViewPropertyAnimator

編輯:Android 技術基礎

本節導讀

上一節我們完成了屬性動畫的入門,本節繼續往裡走一層,談三個進階主題:

  • Evaluator:自訂「值要怎麼從起點過渡到終點」。
  • Interpolator:自訂「時間到進度的映射關係」,也就是速度曲線。
  • ViewPropertyAnimator:官方提供的語法糖,讓 View 動畫寫起來輕eness 許多。

本節內容主要參考郭霖(郭神)的三篇系列文:《Android 屬性動畫完全解析(上)初識屬性動畫的基本用法》、《(中)ValueAnimator 和 ObjectAnimator 的高級用法》、《(下)Interpolator 和 ViewPropertyAnimator 的用法》。


一、Evaluator:決定「怎麼算中間值」

1. 從源碼理解 Evaluator

回想一下,建立 ValueAnimator 的三個靜態方法:ofInt()、ofFloat()、ofObject()。前兩個我們用過,分別處理整數與浮點數的過渡。

那 ofObject() 呢?如果起始值與結束值是兩個自訂物件,「中間那 300 個影格」該長什麼樣子?這就是 Evaluator 的工作:告訴動畫系統如何從初始值過渡到結束值。

翻開 IntEvaluator 的源碼,可以看到它實作 TypeEvaluator 介面並覆寫 evaluate(),三個參數依次是:

  • fraction:動畫完成度(0~1),用來計算目前應該是多少值。
  • startValue:起始值。
  • endValue:結束值。

公式一目了然:

動畫的值 = 初始值 + 完成度 × (結束值 − 初始值)

FloatEvaluator 也是同樣邏輯。因此,只要我們想讓系統懂得如何處理自訂型別,就自己實作 TypeEvaluator 介面即可。

2. 自訂 PointEvaluator 實作

Point.java:一個只有 x、y 的簡單資料物件。

public class Point {
    private float x;
    private float y;

    public Point() { }

    public Point(float x, float y) {
        this.x = x;
        this.y = y;
    }

    public float getX() { return x; }
    public float getY() { return y; }
    public void setX(float x) { this.x = x; }
    public void setY(float y) { this.y = y; }
}

PointEvaluator.java:關鍵就是把 IntEvaluator 的公式套到兩個維度上。

public class PointEvaluator implements TypeEvaluator<Point> {
    @Override
    public Point evaluate(float fraction, Point startValue, Point endValue) {
        float x = startValue.getX() + fraction * (endValue.getX() - startValue.getX());
        float y = startValue.getY() + fraction * (endValue.getY() - startValue.getY());
        return new Point(x, y);
    }
}

AnimView.java:讓圓球從左上角移動到右下角。

public class AnimView extends View {
    public static final float RADIUS = 80.0f;
    private Point currentPoint;
    private Paint mPaint;

    public AnimView(Context context) {
        this(context, null);
    }

    public AnimView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AnimView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(Color.BLUE);
    }

    private void drawCircle(Canvas canvas) {
        float x = currentPoint.getX();
        float y = currentPoint.getY();
        canvas.drawCircle(x, y, RADIUS, mPaint);
    }

    private void startAnimation() {
        Point startPoint = new Point(RADIUS, RADIUS);
        Point endPoint = new Point(getWidth() - RADIUS, getHeight() - RADIUS);

        ValueAnimator anim = ValueAnimator.ofObject(new PointEvaluator(), startPoint, endPoint);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                currentPoint = (Point) animation.getAnimatedValue();
                invalidate();   // 請系統重繪
            }
        });
        anim.setDuration(3000l);
        anim.start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (currentPoint == null) {
            currentPoint = new Point(RADIUS, RADIUS);
            drawCircle(canvas);
            startAnimation();
        } else {
            drawCircle(canvas);
        }
    }
}

MainActivity.java:直接把它設為內容檢視即可。

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new AnimView(this));
    }
}

3. 增強版:移動的同時變色

我們再加一條動畫:圓球移動時顏色從藍漸變為紅。做法是多一個 int color 屬性與 getColor/setColor,然後自訂一個 ColorEvaluator。

ColorEvaluator.java:顏色本質是 ARGB 四個分量,分別插值再組回來。

public class ColorEvaluator implements TypeEvaluator<Integer> {
    @Override
    public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
        int alpha = (int) (Color.alpha(startValue)
                + fraction * (Color.alpha(endValue) - Color.alpha(startValue)));
        int red = (int) (Color.red(startValue)
                + fraction * (Color.red(endValue) - Color.red(startValue)));
        int green = (int) (Color.green(startValue)
                + fraction * (Color.green(endValue) - Color.green(startValue)));
        int blue = (int) (Color.blue(startValue)
                + fraction * (Color.blue(endValue) - Color.blue(startValue)));
        return Color.argb(alpha, red, green, blue);
    }
}

AnimView2.java:用 AnimatorSet 把位移與變色兩條動畫綁在一起。

public class AnimView2 extends View {
    public static final float RADIUS = 80.0f;
    private Point currentPoint;
    private Paint mPaint;
    private int mColor;

    public AnimView2(Context context) {
        this(context, null);
    }

    public AnimView2(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AnimView2(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(Color.BLUE);
    }

    private void drawCircle(Canvas canvas) {
        float x = currentPoint.getX();
        float y = currentPoint.getY();
        canvas.drawCircle(x, y, RADIUS, mPaint);
    }

    private void startAnimation() {
        Point startPoint = new Point(RADIUS, RADIUS);
        Point endPoint = new Point(getWidth() - RADIUS, getHeight() - RADIUS);

        ValueAnimator anim = ValueAnimator.ofObject(new PointEvaluator(), startPoint, endPoint);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                currentPoint = (Point) animation.getAnimatedValue();
                invalidate();
            }
        });

        ObjectAnimator objectAnimator = ObjectAnimator.ofObject(
                this, "color", new ColorEvaluator(), Color.BLUE, Color.RED);

        // with 表示同時播放
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(anim).with(objectAnimator);
        animatorSet.setStartDelay(1000l);
        animatorSet.setDuration(3000l);
        animatorSet.start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (currentPoint == null) {
            currentPoint = new Point(RADIUS, RADIUS);
            drawCircle(canvas);
            startAnimation();
        } else {
            drawCircle(canvas);
        }
    }

    // ObjectAnimator 靠這組 getter/setter 運作
    public int getColor() {
        return mColor;
    }

    public void setColor(int color) {
        mColor = color;
        mPaint.setColor(color);
        invalidate();
    }
}

MainActivity 裡把 AnimView 換成 AnimView2 就能看到效果。


二、Interpolator:決定「速度曲線」

補間動畫那一節已經介紹過這批補間器,而它們在屬性動畫中同樣通用。此外屬性動畫引入了 TimeInterpolator 介面以相容舊有的 Interpolator,因此過去所有的 Interpolator 實作都能直接拿來用。設定方式是呼叫動畫物件(或 AnimatorSet)的 setInterpolator()。

讓小球從畫面頂端正中落下:

animatorSet.setInterpolator(new AccelerateInterpolator(2f));   // 括號內為加速度係數

落得很快但沒有反彈,看起來不太自然。換成 BounceInterpolator 試試:

就對味了。系統還內建了許多 Interpolator,值得逐一試用。

1. Interpolator 的內部機制

翻到 TimeInterpolator 介面,只有一個方法:getInterpolation(float input)。

關鍵理解:input 會隨動畫推進而不斷變化,規律是「依設定時長均勻增加」,範圍 0 到 1。動畫開始時 input = 0,結束時 input = 1,中間依進度線性遞增。

而 getInterpolation() 的回傳值,就是 TypeEvaluator 裡那個 fraction。也就是說:

input(時間進度)→ Interpolator 轉換 → fraction(值進度)→ Evaluator 計算 → 實際數值

看 LinearInterpolator 的源碼最清楚——它什麼都沒做,直接把 input 回傳,所以 fraction 等於 input,這就是等速運動:

換句話說,Interpolator 的差異純粹就是演算法不同,而演算法背後是數學。例如 BounceInterpolator:

再挑一個比較好理解的 AccelerateDecelerateInterpolator(先加速後減速):

它的核心式子是:

(float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f

推導過程:input 範圍 [0, 1],所以 (input + 1) * π 落在 [π, 2π],而 cos 在這個區間的值從 −1 增到 1;除以 2 再加 0.5 之後,輸出範圍回到 [0, 1]。因為 cos 在區間末端的斜率變化率不同,整體呈現「起步慢、中段快、收尾慢」的曲線:

這裡再次體會到數學的重要性。

2. 自訂 Interpolator

實作 TimeInterpolator 介面、覆寫 getInterpolation 即可。以下範例做出「先減速、再加速」的曲線:

private class DecelerateAccelerateInterpolator implements TimeInterpolator {
    @Override
    public float getInterpolation(float input) {
        if (input < 0.5) {
            return (float) (Math.sin(input * Math.PI) / 2);
        } else {
            return 1 - (float) (Math.sin(input * Math.PI) / 2);
        }
    }
}

使用時:setInterpolator(new DecelerateAccelerateInterpolator())。


三、ViewPropertyAnimator:更簡潔的寫法

這是 API 16 之後為 View 動畫量身打造的便捷工具。同樣的效果,兩種寫法對比如下:

// 傳統寫法
ObjectAnimator animator = ObjectAnimator.ofFloat(textview, "alpha", 0f);
animator.start();

// ViewPropertyAnimator
textview.animate().alpha(0f);

它還支援串接語法,把多個動畫、時長、補間器串成一串:

textview.animate().x(500).y(500)
        .setDuration(5000)
        .setInterpolator(new BounceInterpolator());

使用上有三個細節要理解:

  • 整個機制建立在 View 類別新增的 animate() 方法上,該方法會建立並回傳一個 ViewPropertyAnimator 實例,後續所有設定都作用於這個實例。
  • 動畫定義完成後會自動啟動,不需要(也不建議)再呼叫 start()。串接模式下也是一樣:只要還在不斷串接新方法,動畫就會等待;等所有設定都完成,才自動開始。
  • 所有方法都回傳自身的實例,因此能一路串下去,一行程式碼完成相當複雜的動畫組合。

內部差異值得一提:ObjectAnimator 每次更新屬性都會 invalidate 一次;ViewPropertyAnimator 則會把同一影格內的多個屬性變更合併,只觸發一次重繪。這也是它在效能上通常更好的原因。


本節範例與延伸

AnimatorDemo3.zip

另外推薦 GitHub 上的開源動畫合集專案 BaseAnimation,收錄了大量動畫效果,想研究各種炫技實作可以直接翻源碼。


本節回顧

本節把屬性動畫的三個進階拼圖補齊:Evaluator 決定「值怎麼算」,Interpolator 決定「時間怎麼映射到進度」,ViewPropertyAnimator 決定「程式碼能多短」。理解這三者之後,動畫就不再是照抄範例,而是可以從需求反推設計。

這也是「繪圖與動畫」章節的最後一節。把這一章的內容消化完,再去碰自訂控制項或閱讀別人的自訂 View 原始碼,應該不會再被一堆陌生 API 擋在門外。

再次感謝郭神的三篇系列文,本節屬性動畫部分大量引用了其中的說明與示意圖。

PS:後面的示意圖換成模擬器,是因為實機的 N5 罷工了。

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