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

Android 屬性動畫入門:從 ObjectAnimator 到自訂 TypeEvaluator

編輯:關於 Android 程式設計

網路上高手的開場白往往先談心境、聊生活,我這裡就省掉鋪墊,直接進主題——因為這東西本來就不難。

動畫的兩套體系

Android 的動畫效果繞不開四件事:位移、縮放、旋轉、透明度。實現路徑有兩條:Animation 與 Animator。它們的思維模式完全不同。

1. 傳統的 View 動畫

傳統動畫的原理是:系統在動畫期間不斷調用 onDraw 重繪界面,靠一幀一幀的畫面變化營造出「動起來」的錯覺。

public void move(View view) {
    TranslateAnimation animation = new TranslateAnimation(0, 200, 0, 0);
    animation.setDuration(1000);
    animation.setFillAfter(true);
    imageView.startAnimation(animation);
}

這段程式碼讓 ImageView 沿 X 軸平移 200 像素。看起來達成了效果,但問題在於:它只改變了「畫在哪裡」,沒有改變「點擊事件落在哪裡」。你可以在移動後給它掛個點擊監聽試試,會發現觸摸區域仍停在原位。

也就是說,傳統動畫無法勝任需要與用戶交互的場景;再加上它會持續觸發 onDraw,額外消耗 CPU,而效果又只有位移、縮放、旋轉、透明度這四種。於是從 Android 3.0 開始,Google 推出了屬性動畫。

2. 屬性動畫(3.0 之後)

Animator 如其名,操作的是屬性的 get/set 方法,真正去改動一個屬性的值。既然值真的變了,那麼绘制位置與事件響應位置自然一致。

幾個高頻屬性:透明度 alpha、Z 軸旋轉 rotation、X/Y 軸旋轉 rotationX/rotationY、水平與垂直偏移 translationX/translationY。

// 寫法一:一個屬性一個 ObjectAnimator
ObjectAnimator.ofFloat(imageView, "translationY", 0F, 200F).setDuration(1000).start();
ObjectAnimator.ofFloat(imageView, "translationX", 0F, 200F).setDuration(1000).start();
ObjectAnimator.ofFloat(imageView, "rotation", 0F, 360F).setDuration(1000).start();

// 寫法二:用 PropertyValuesHolder 合併多個屬性
PropertyValuesHolder p1 = PropertyValuesHolder.ofFloat("translationY", 0F, 200F);
PropertyValuesHolder p2 = PropertyValuesHolder.ofFloat("translationX", 0F, 200F);
PropertyValuesHolder p3 = PropertyValuesHolder.ofFloat("rotation", 0F, 360F);
ObjectAnimator.ofPropertyValuesHolder(imageView, p1, p2, p3).setDuration(1000).start();

兩種寫法效果一致,跑一遍就知道手感如何。

如果還想控制多個動畫的執行順序,就用 AnimatorSet:

ObjectAnimator animator1 = ObjectAnimator.ofFloat(imageView, "translationY", 0F, 150F);
ObjectAnimator animator2 = ObjectAnimator.ofFloat(imageView, "translationX", 0F, 150F);
ObjectAnimator animator3 = ObjectAnimator.ofFloat(imageView, "rotation", 0F, 180F);
ObjectAnimator animator4 = ObjectAnimator.ofFloat(imageView, "alpha", 0F, 1F);

AnimatorSet set = new AnimatorSet();
// 同時執行
// set.playTogether(animator1, animator2, animator3);
// 依序執行
// set.playSequentially(animator1, animator2, animator3);

// 更靈活的編排:1 和 2 同時,接著 3,最後 4
set.play(animator1).with(animator2);
set.play(animator3).after(animator2);
set.play(animator4).after(animator3);
set.setDuration(1000);
set.start();

3. 動畫監聽

監聽寫起來非常直觀,繼承 AnimatorListenerAdapter 只重寫需要的回調即可,不必把空方法全部實作一遍:

public void alphaClick(View view) {
    ObjectAnimator animator = ObjectAnimator.ofFloat(view, "alpha", 0F, 1F);
    animator.setDuration(1000);
    animator.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            Toast.makeText(MainActivity.this, "anmi end", Toast.LENGTH_SHORT).show();
        }
    });
    animator.start();
}

點一下控件,透明度在 1 秒內完成變化,結束後彈出提示。

4. 一個小例子:扇形散開的圖標

布局很簡單,用 FrameLayout 把七張圖片層層疊放:

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView android:id="@+id/image_b" android:src="@mipmap/b"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <ImageView android:id="@+id/image_c" android:src="@mipmap/c"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <ImageView android:id="@+id/image_d" android:src="@mipmap/d"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <ImageView android:id="@+id/image_e" android:src="@mipmap/e"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <ImageView android:id="@+id/image_f" android:src="@mipmap/f"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <ImageView android:id="@+id/image_g" android:src="@mipmap/g"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <ImageView android:id="@+id/image_a" android:src="@mipmap/a"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />
</FrameLayout>

Java 端在 onCreate 裡把 ImageView 收進 List,然後綁定點擊事件:

public class myActivity extends Activity implements View.OnClickListener {

    private int[] res = {R.id.image_a, R.id.image_b, R.id.image_c, R.id.image_d,
            R.id.image_e, R.id.image_f, R.id.image_g};
    private List<ImageView> imageViewList = new ArrayList<>();
    private boolean flag = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activit_my);
        for (int i = 0; i < res.length; i++) {
            ImageView imageView = (ImageView) findViewById(res[i]);
            imageView.setOnClickListener(this);
            imageViewList.add(imageView);
        }
    }

    @Override
    public void onClick(View v) {
        if (flag) {
            for (int i = 0; i < res.length; i++) {
                ObjectAnimator animator =
                        ObjectAnimator.ofFloat(imageViewList.get(i), "translationY", 0F, -300F);
                animator.setDuration(500);
                animator.setStartDelay(i * 100);
                animator.start();
            }
            flag = false;
        } else {
            for (int i = 0; i < res.length; i++) {
                ObjectAnimator animator =
                        ObjectAnimator.ofFloat(imageViewList.get(i), "translationY", -300F, 0F);
                animator.setDuration(500);
                animator.setStartDelay(i * 100);
                animator.start();
            }
            flag = true;
        }
    }
}

上面實現的是直線上下的效果。如果想改成扇形散開,只需要把位移拆成 X、Y 兩個分量,用三角函數算角度:

float angle;
final int r = 380;
angle = (float) Math.PI / (2 * (res.length - 2));
for (int i = 1; i < res.length; i++) {
    float xLength = (float) (r * Math.sin((i - 1) * angle));
    float yLength = (float) (r * Math.cos((i - 1) * angle));
    ObjectAnimator animator1 = ObjectAnimator.ofFloat(imageViewList.get(i), "translationX", 0F, -xLength);
    ObjectAnimator animator2 = ObjectAnimator.ofFloat(imageViewList.get(i), "translationY", 0F, -yLength);
    AnimatorSet set = new AnimatorSet();
    set.playTogether(animator1, animator2);
    set.setDuration(500);
    set.setInterpolator(new BounceInterpolator());
    set.setStartDelay(i * 200);
    set.start();
    flag = true;
}

5. ValueAnimator:一切都從數值開始

ValueAnimator 是 ObjectAnimator 的父類。它本身不作用於任何屬性,也不提供任何預設動畫,它只做一件事——產生數值。有了這個不斷變化的值,你就能拿它去做任何事。

比如點一下按鈕,讓上面的文字從 0 一路加到 100:

public void ValueClick(View view) {
    final Button button = (Button) view;
    ValueAnimator animator = ValueAnimator.ofInt(0, 100);
    animator.setDuration(5000);
    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            Integer value = (Integer) animation.getAnimatedValue();
            button.setText("" + value);
        }
    });
    animator.start();
}

數值也可以自訂型別。搭配 TypeEvaluator,就能讓一個物件沿著自訂軌跡運動:

ValueAnimator animator1 = ValueAnimator.ofObject(new TypeEvaluator<PointF>() {
    @Override
    public PointF evaluate(float fraction, PointF startValue, PointF endValue) {
        float x = (endValue.x - startValue.x) * fraction;
        float y = (endValue.y - startValue.y) * fraction;
        button.setX(x);
        button.setY(y);
        return null;
    }
}, new PointF(1, 1), new PointF(300, 300));
animator1.setDuration(3000);
animator1.start();

小結一下:屬性動畫的價值在於「真的改了值」,因此事件分發、控件狀態都跟得上;而 ValueAnimator 是所有屬性動畫的地基,掌握它就掌握了自訂動畫的自由度。

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