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

Android 三維旋轉動畫實作與封裝:支援 X、Y、Z 三軸旋轉

編輯:關於 Android 開發

本文介紹如何在 Android 中實作 3D(立體)旋轉動畫,並把它封裝成一個可重複使用的自訂 Animation 類別。以下是我實作出來的成果:

一、立體旋轉的三種類型

1. 以 X 軸為軸心旋轉
2. 以 Y 軸為軸心旋轉
3. 以 Z 軸為軸心旋轉 —— 這一種等價於 Android 自帶的平面旋轉動畫 RotateAnimation

二、實作的核心步驟

1. 繼承 Animation,重寫 applyTransformation
透過回呼參數 float interpolatedTime, Transformation t 來控制動畫:interpolatedTime 用來計算當前旋轉角度,t 則用來取得並操作變換矩陣,从而实现圖像的旋轉。

2. 使用 android.graphics.Camera 控制旋轉演算法
Camera 可以對圖像執行比較複雜的操作——旋轉、綻放,並能與 Matrix 搭配實現圖像的傾斜與景深效果。

三、核心類別封裝:Rotate3dAnimation

package rotateanim.example.com.androidrotateanim;

import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.graphics.Camera;
import android.graphics.Matrix;

/**
 * 在 X、Y、Z 軸之間旋轉 View 的動畫類別。
 * 同時在 Z 軸上加入位移(景深),使效果更立體。
 */
public class Rotate3dAnimation extends Animation {

    public static final Byte ROTATE_X_AXIS = 0x00;
    public static final Byte ROTATE_Y_AXIS = 0x01;
    public static final Byte ROTATE_Z_AXIS = 0x02;

    private final float mFromDegrees;
    private final float mToDegrees;
    private final float mCenterX;
    private final float mCenterY;
    private final float mDepthZ;
    private final boolean mReverse;
    private Camera mCamera;

    private Byte mRotateAxis;   // 0:X軸 1:Y軸 2:Z軸

    /**
     * @param fromDegrees 起始角度
     * @param toDegrees   結束角度
     * @param centerX     旋轉中心的 X 座標
     * @param centerY     旋轉中心的 Y 座標
     * @param depthZ      Z 軸上的景深位移量
     * @param rotateAxis  旋轉所依據的軸
     * @param reverse     true 表示由近到遠,false 表示由遠到近
     */
    public Rotate3dAnimation(float fromDegrees, float toDegrees,
                             float centerX, float centerY, float depthZ,
                             Byte rotateAxis, boolean reverse) {
        mFromDegrees = fromDegrees;
        mToDegrees = toDegrees;
        mCenterX = centerX;
        mCenterY = centerY;
        mDepthZ = depthZ;
        mRotateAxis = rotateAxis;
        mReverse = reverse;
    }

    @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 t) {
        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 = t.getMatrix();

        // 先保存相機目前位置,動畫結束後才能復原
        camera.save();

        if (mReverse) {
            // z 偏移越來越大,形成由近到遠的效果
            camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
        } else {
            // z 偏移越來越小,形成由遠處飛向眼前、越來越近的效果
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        }

        // 依指定軸加上旋轉效果
        if (ROTATE_X_AXIS.equals(mRotateAxis)) {
            camera.rotateX(degrees);
        } else if (ROTATE_Y_AXIS.equals(mRotateAxis)) {
            camera.rotateY(degrees);
        } else {
            camera.rotateZ(degrees);
        }

        // 把一連串變換套用到矩陣上,之後即可復原 camera 位置
        camera.getMatrix(matrix);
        camera.restore();

        // 以下兩句確保動畫以 View 中心為旋轉中心
        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);
    }
}

四、使用方式

用法與一般動畫完全相同:建立物件、設定 duration、丟給 View 啟動即可。

// mRotateImgv 就是需要旋轉的 View 物件

/** 以 X 軸為軸心旋轉 */
private void rotateOnXCoordinate() {
    float centerX = mRotateImgv.getWidth() / 2.0f;
    float centerY = mRotateImgv.getHeight() / 2.0f;
    float depthZ = 0f;

    Rotate3dAnimation rotate3dAnimationX = new Rotate3dAnimation(
            0, 180, centerX, centerY, depthZ, Rotate3dAnimation.ROTATE_X_AXIS, true);
    rotate3dAnimationX.setDuration(1000);
    mRotateImgv.startAnimation(rotate3dAnimationX);
}

/** 以 Y 軸為軸心旋轉 */
private void rotateOnYCoordinate() {
    float centerX = mRotateImgv.getWidth() / 2.0f;
    float centerY = mRotateImgv.getHeight() / 2.0f;
    float centerZ = 0f;

    Rotate3dAnimation rotate3dAnimationY = new Rotate3dAnimation(
            0, 180, centerX, centerY, centerZ, Rotate3dAnimation.ROTATE_Y_AXIS, true);
    rotate3dAnimationY.setDuration(1000);
    mRotateImgv.startAnimation(rotate3dAnimationY);
}

/** 以 Z 軸為軸心旋轉 —— 等價於普通平面旋轉動畫 */
private void rotateAnimHorizon() {
    float centerX = mRotateImgv.getWidth() / 2.0f;
    float centerY = mRotateImgv.getHeight() / 2.0f;
    float centerZ = 0f;

    Rotate3dAnimation rotate3dAnimationZ = new Rotate3dAnimation(
            180, 0, centerX, centerY, centerZ, Rotate3dAnimation.ROTATE_Z_AXIS, true);
    rotate3dAnimationZ.setDuration(1000);
    mRotateImgv.startAnimation(rotate3dAnimationZ);

    // 也可以直接用系統自帶的旋轉動畫:
    // RotateAnimation rotateAnimation = new RotateAnimation(0, 180,
    //         Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    // rotateAnimation.setDuration(1000);
    // mRotateImgv.startAnimation(rotateAnimation);
}

五、幾個實作要點

為什麼要 preTranslate / postTranslate?
Camera 的旋轉是以原點為中心,若不先把座標系平移到 View 中心,物件會繞著左上角翻轉。先 pre 平移負的中心座標、變換後再 post 平移回來,就能實現「繞中心旋轉」。

記得呼叫 save() 與 restore()
Camera 是可變狀態的物件,每次動畫都會改動它。用完必須 restore,否則下一次動畫會在錯誤的基準上計算,造成位移錯亂。

modern 寫法建議
本範例屬於 View Animation 體系。在新專案中,若想呈現卡片翻轉效果,更推薦使用 ViewPropertyAnimator 搭配 rotationX / rotationY,或直接採用官方提供的 CardFlip 範例(以 AnimatorSet 串接 Fragment 的 showAsDropDown 動畫),程式碼更短且效能更好。

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