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

Android 打造 3D Y 軸翻轉動畫:RotateAnimation 與 Camera 的組合技

編輯:關於 Android 程式設計

系統內建的 RotateAnimation 只能做平面旋轉,也就是繞著螢幕垂直方向轉。想要做出卡片翻面、門片開闔那種帶景深的 3D 效果,就得自己動手——而 Android 早就把工具準備好了:Camera 類。

3D 動畫的三個關鍵類別是 Animation(定義動畫參數)、Camera(提供 3D 視角變換)、Matrix(承載最終的變換矩陣)。三者搭配,就能繞 X、Y、Z 任一軸做出透視旋轉。

呼叫端:先取得控制項尺寸

這裡有個經典陷阱:在 onCreate() 中直接呼叫 getWidth(),拿到的會是 0。因為此時界面尚未完成測量與配置,控制項還沒被繪製出來。解法是透過 ViewTreeObserver 監聽布局完成:

public class MainActivity extends Activity {
    private ImageButton ib;
    float w, y;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 在 onCreate 中取得 ImageButton 的實際尺寸
        ViewTreeObserver vto = ib.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ib.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                w = ib.getWidth();
                y = ib.getHeight();
                rotateAnim(w, y);
            }
        });
    }

    /** 啟動旋轉動畫 */
    private void rotateAnim(float w, float y) {
        final float centerX = w / 2.0f;
        final float centerY = y / 2.0f;

        RotateAnimation rotation = new RotateAnimation(
                0, -360, centerX, centerY, 310.0f, false);

        rotation.setDuration(1500);                              // 動畫時長
        rotation.setFillAfter(true);                             // 結束後保持姿態
        rotation.setInterpolator(new DecelerateInterpolator());  // 減速曲線
        rotation.setRepeatCount(Animation.INFINITE);             // 無限重複
        rotation.setRepeatMode(Animation.RESTART);               // 重播模式

        ib.startAnimation(rotation);
    }
}

注意監聽器裡第一行一定要先把自己移除,否則每次布局變動都會重複觸發,動畫會疊在一起。

自訂 RotateAnimation 類

/**
 * 3D 旋轉動畫
 * 三個關鍵類:Animation / Camera / Matrix
 */
public class RotateAnimation extends Animation {
    private final float mFromDegrees;  // 起始角度
    private final float mToDegrees;    // 結束角度
    private final float mCenterX;      // 中心座標 X
    private final float mCenterY;      // 中心座標 Y
    private final boolean mReverse;    // 是否反向
    private Camera mCamera;

    public RotateAnimation(float fromDegrees, float toDegrees,
                           float centerX, float centerY,
                           float depthZ, boolean reverse) {
        mFromDegrees = fromDegrees;
        mToDegrees = toDegrees;
        mCenterX = centerX;
        mCenterY = centerY;
        mReverse = reverse;
    }

    /** 初始化動畫物件尺寸,Camera 在此建立 */
    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        mCamera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation tran) {
        final float fromDegrees = mFromDegrees;
        float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

        final float centerX = mCenterX;
        final float centerY = mCenterY;
        final Camera camera = mCamera;
        final Matrix matrix = tran.getMatrix();

        camera.save();   // 保存狀態
        if (mReverse) {
            camera.translate(0.0f, 0.0f, 0.0f);
        } else {
            camera.translate(0.0f, 0.0f, 0.0f);
        }

        camera.rotateY(degrees);   // 繞 Y 軸旋轉;改成 rotateX / rotateZ 即可換軸
        camera.getMatrix(matrix);

        camera.restore();  // 恢復狀態

        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);
    }
}

關鍵在最後兩行

preTranslate 與 postTranslate 是一對,作用是「把旋轉中心搬回原點、轉完再搬回去」。少了這兩行,控制項會繞著整個畫布的左上角翻轉,而不是繞著自己中心——這是自製 3D 動畫最常犯的錯。

另外,若要做出真正的「背面」效果(旋轉超過 90 度後顯示另一張圖),需要在 applyTransformation 中判斷角度並切換可見性,這部分可依需求自行擴充。

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