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

Android 動畫全景解析:View 動畫、幀動畫與屬性動畫

編輯:關於 Android 程式設計

動畫是面試高頻考點,也是提升產品質感的關鍵。Android 動畫分三大類,先建立整體認知:

  • View 動畫(補間動畫):通過平移、縮放、旋轉、透明度變化做漸進式變換。
  • 幀動畫:不停切換圖片形成動畫。
  • 屬性動畫:持續改變對象屬性值來驅動動畫。

一、View 動畫

1. 系統提供的四種

可以在 res/anim/ 下用 <translate>、<scale>、<rotate>、<alpha> 四個標簽配置,多個動畫用 <set> 組合。啟動方式一行搞定:

view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.myanimation));

同樣的邏輯也能用 Java 寫:

splash = (RelativeLayout) findViewById(R.id.splash);

// 旋轉
RotateAnimation rotateAnimation = new RotateAnimation(0, 360,
        Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotateAnimation.setDuration(2000);
rotateAnimation.setFillAfter(true);

// 縮放
ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 0, 1,
        Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnimation.setDuration(2000);
scaleAnimation.setFillAfter(true);

// 透明度
AlphaAnimation alphaAnimation = new AlphaAnimation(0.2f, 1.0f);
alphaAnimation.setDuration(2000);
alphaAnimation.setFillAfter(true);

// 平移
TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 100, 100);
translateAnimation.setDuration(2000);
translateAnimation.setFillAfter(true);

// 組合
AnimationSet animationSet = new AnimationSet(true);
animationSet.addAnimation(rotateAnimation);
animationSet.addAnimation(scaleAnimation);
animationSet.addAnimation(alphaAnimation);
animationSet.addAnimation(translateAnimation);

splash.startAnimation(animationSet);

2. 自定義 View 動畫

實際項目中較少見。做法:繼承 Animation,重寫 initialize()(初始化)與 applyTransformation()(矩陣變換)。

3. 為 ViewGroup 的所有子元素設置動畫

使用 android:layoutAnimation 即可讓容器內的子元素依次進場:

// res/anim/layout_anim.xml
<layoutAnimation xmlns:android="https://schemas.android.com/apk/res/android"
    android:delay="0.1"                 // 每個子元素延遲 0.1*T
    android:animationOrder="normal"     // normal / reverse / random
    android:animation="@anim/layout_anim_item"/>

// res/anim/layout_anim_item.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="200"                                   // 單個子元素週期 T
    android:interpolator="@android:anim/accelerate_interpolator"
    android:shareInterpolator="true">                       // 共享插值器
    <alpha android:fromAlpha="0.2" android:toAlpha="1.0"/>
    <translate android:fromXDelta="100" android:toXDelta="0"/>
</set>

4. 為 Activity 切換設置動畫

在 startActivity() 之後調用:

overridePendingTransition(R.anim.tran_in, R.anim.tran_out);
// res/anim/tran_in.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="500"
    android:fromXDelta="100%p"
    android:fromYDelta="0"
    android:toXDelta="0"
    android:toYDelta="0" >
</translate>

對應的 tran_out 只需把 toXDelta 改成 -100%p。

二、幀動畫

本質是逐幀切換 Drawable,實現簡單,但最容易 OOM,使用時務必控制單幀圖片尺寸。

// res/drawable/myanimation.xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="https://schemas.android.com/apk/res/android"
    android:oneshot="false" >      // false 循環播放
    <item android:drawable="@drawable/drawable1" android:duration="200"/>
    <item android:drawable="@drawable/drawable2" android:duration="200"/>
</animation-list>

// 代碼中加載並啟動
view.setBackgroundResource(R.drawable.myanimation);
((AnimationDrawable) view.getBackground()).start();

三、屬性動畫

View 動畫有個致命缺陷:它並沒有真正改變 View 的 left/top/right/bottom,只是系統臨時繪製的結果,因此點擊區域仍停留在原位。從 Android 3.0 開始,屬性動畫填補了這個空白。

屬性動畫的做法是改變新增屬性(translationX/Y、scaleX/Y、rotationX/Y 等)並刷新畫面,點擊位置會實時跟著變。但它同樣不改變原始的上下左右四個值。此外,屬性動畫的作用對象不限於 View,任何對象都可以。

1. setTranslationX

view.setTranslationX(x);                              // 3.0 之後
ViewHelper.setTranslationX(view, x);                  // 3.0 之前,依賴 NineOldAndroid

2. ValueAnimator

只負責定義和驅動動畫流程,不直接操作屬性,需要自己加更新監聽:

ValueAnimator animator = ValueAnimator.ofInt(1, 100);
animator.addUpdateListener(new AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        float fraction = animation.getAnimatedFraction();   // 動畫進度 0~1
        // IntEvaluator 幫我們算出 start + (end - start) * fraction
        view.getLayoutParams().width = (Integer) new IntEvaluator().evaluate(fraction, start, end);
        view.requestLayout();
    }
});
animator.setDuration(1000).start();

3. ObjectAnimator

繼承自 ValueAnimator,可以直接改目標屬性:

// x 軸方向放大到 2 倍
ObjectAnimator animator = ObjectAnimator.ofFloat(view, "scaleX", 2.0f);
animator.setDuration(1000);
animator.setStartDelay(1000);
animator.start();

大多數場景用它就夠了。但它有前提:目標屬性必須提供 get/set 方法,因為它的原理就是反覆調用 setter 更新值;若沒傳初始值,還會自動去調 getter。遇到沒有對應方法的屬性時,官方建議包一層中間對象:

ViewWrapper wrapper = new ViewWrapper(view);
ObjectAnimator.ofInt(wrapper, "width", 200).setDuration(1000).start();

private static class ViewWrapper {
    private View myView;
    public ViewWrapper(View view) { myView = view; }
    public int getWidth() { return myView.getLayoutParams().width; }
    public int setWidth(int width) {
        myView.getLayoutParams().width = width;
        myView.requestLayout();
    }
}

4. ViewPropertyAnimator

來自 NineOldAndroid 庫,寫法更鏈式簡潔,同時兼容 3.0 以下版本:

ViewPropertyAnimator.animate(view).scaleX(2.0f)
        .setDuration(1000)
        .setInterpolator(new OvershootInterpolator())
        .setStartDelay(1000)
        .start();

5. AnimatorSet

把多個動畫組合起來,並可控制時序關係:

ObjectAnimator anim1 = ObjectAnimator.ofFloat(view, "alpha", 1.0f, 0f);
ObjectAnimator anim2 = ObjectAnimator.ofFloat(view, "translationY", 0f, 30f);
ObjectAnimator anim3 = ObjectAnimator.ofFloat(view, "translationX", 0f, 30f);

AnimatorSet animatorSet = new AnimatorSet();
animatorSet.setDuration(5000);
animatorSet.setInterpolator(new LinearInterpolator());
// 三個同時播放
// animatorSet.playTogether(anim1, anim2, anim3);
// 1、2 同時,3 排在 2 之後
animatorSet.play(anim1).with(anim2);
animatorSet.play(anim3).after(anim2);
animatorSet.start();

四、插值器

系統已內置一批插值器,都實現了 Interpolator 接口。

自定義很簡單:Interpolator 繼承自 TimeInterpolator,後者定義了 getInterpolation(float input),參數是 0~1 的完成進度。覆寫它即可改變速度曲線。以下是一個「兩頭慢、中間快」的實現:

public class AccelerateDecelerateInterpolator extends BaseInterpolator
        implements NativeInterpolatorFactory {
    @Override
    public float getInterpolation(float input) {
        return (float) (Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
    }
}

五、動畫監聽

需要接續業務邏輯時,給動畫設置 Animation.AnimationListener,可監聽開始、結束、重複、取消四個時機:

animationSet.setAnimationListener(new Animation.AnimationListener() {
    @Override public void onAnimationStart(Animation animation) {}
    @Override public void onAnimationEnd(Animation animation) {}
    @Override public void onAnimationRepeat(Animation animation) {}
    @Override public void onAnimationCancel(Animation animation) {}
});

若關心每一幀的回調,則使用 AnimatorUpdateListener 並重寫 onAnimationUpdate()。

選型上的一般結論:簡單的進場退場用 View 動畫或 ViewPropertyAnimator;序列圖用幀動畫但要控體積;需要真正改動交互屬性、或作用於非 View 對象時,用屬性動畫。

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