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

Android 3D 旋轉動畫實作:Camera 與 Matrix 的配合

編輯:關於 Android 程式設計

前面兩篇講的都是 2D 動畫。Android 並沒有直接提供 3D 動畫介面,所以想要做出翻牌、立體旋轉這類效果,必須自己繼承 Animation 類,並借助 Camera 與 Matrix 完成透視投影。

核心原理是這樣的:2D 的 Matrix 只能做平移、旋轉、縮放與切變,這些都是平面上的線性變換,無法表現「近大遠小」的透視感。而 android.graphics.Camera 內部維護一個真正的 3D 矩陣,呼叫它的 rotateX / rotateY / translate 之後,再透過 getMatrix() 把結果取出來套用到 View 上——透視的效果就在這一步裡被計算進去了。

一、自定義 3D 動畫類

package com.xjp.animator;

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

public class My3dAnimation extends Animation {

    private final float mFromDegrees;
    private final float mToDegrees;
    private final float mCenterX;
    private final float mCenterY;
    private final float mDepthZ;

    private Camera mCamera;
    private int mDirection;

    private final static int ROTATE_X = 0;   // 沿 x 軸旋轉
    private final static int ROTATE_Y = 1;   // 沿 y 軸旋轉

    /**
     * 沿指定軸線建立 3D 旋轉動畫。
     *
     * @param direction   3D 旋轉的方向(ROTATE_X 或 ROTATE_Y)
     * @param fromDegrees 起始角度
     * @param toDegrees   結束角度
     * @param centerX     旋轉中心的 X 座標
     * @param centerY     旋轉中心的 Y 座標
     * @param depthZ      Z 軸(深度)方向的位移量
     */
    public My3dAnimation(int direction, float fromDegrees, float toDegrees,
                         float centerX, float centerY, float depthZ) {
        mDirection = direction;
        mFromDegrees = fromDegrees;
        mToDegrees = toDegrees;
        mCenterX = centerX;
        mCenterY = centerY;
        mDepthZ = depthZ;
    }

    @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 (centerX != 0) {
            if (interpolatedTime < 0.5) {
                camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
            } else {
                camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
            }
        }

        switch (mDirection) {
            case ROTATE_X:
                camera.rotateX(degrees);
                break;
            case ROTATE_Y:
                camera.rotateY(degrees);
                break;
        }

        camera.getMatrix(matrix);
        camera.restore();

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

幾個關鍵設計

Camera 在 initialize() 中建立。initialize() 只在動畫第一次載入時呼叫一次,適合放一次性資源。若放在 applyTransformation() 裡,動畫每一帧都會 new 一個 Camera,幀數一多就是嚴重的效能與記憶體問題。

applyTransformation 的 interpolatedTime。這個參數是 0.0 到 1.0 之間的插值進度,已經過 Interpolator 運算。用它做線性內插(fromDegrees + (toDegrees - fromDegrees) * interpolatedTime)就能得到當前帧的角度,這是 Android 動畫最基本的計算模式。

那個 Z 軸位移在做什麼。if (interpolatedTime < 0.5) 這段是個小細節:動畫前半段把物件往鏡頭方向推近(z 遞增),後半段再推遠。這能減弱旋轉到 90 度時物件幾乎消失的那個尷尬瞬間,讓翻轉看起來更有立體感。centerX 為 0 時跳過這段,是為了給呼叫方一個「不要 Z 軸效果」的開關。

pre/postTranslate 的順序不可顛倒。Matrix 的乘法順序直接影響結果:

matrix.preTranslate(-centerX, -centerY);   // 把旋轉中心移到原點
matrix.postTranslate(centerX, centerY);    // 再移回去

pre 是「在現有變換之前先套用」,post 是「之後再套用」。所以整體效果是:先平移讓旋轉中心對齊原點、執行 Camera 給出的 3D 變換、最後平移回原位。少了這兩行,物件會繞著螢幕左上角旋轉而不是繞自身中心。

camera.save() 與 camera.restore()。Camera 內部是有狀態的,save/restore 確保每次套用不互相污染。雖然這裡每帧只操作一次,養成習慣可以避免後續擴充時出問題。

二、使用範例

package com.xjp.animator;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.app.Activity;

public class MainActivity extends Activity implements View.OnClickListener {

    private ImageView img1;
    private ImageView img2;
    private ImageView img3;
    private ViewGroup mContainer;

    private final static int ROTATE_X = 0;
    private final static int ROTATE_Y = 1;

    private My3dAnimation my3dAnimation;

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

    private void findViews() {
        mContainer = (ViewGroup) findViewById(R.id.container);
        mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);

        img1 = (ImageView) findViewById(R.id.img_left);
        img1.setOnClickListener(this);
        img2 = (ImageView) findViewById(R.id.img_right);
        img2.setOnClickListener(this);
        img3 = (ImageView) findViewById(R.id.img_3);
        img3.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        float centerX = v.getWidth() / 2.0f;
        float centerY = v.getHeight() / 2.0f;

        if (v.getId() == R.id.img_left) {
            my3dAnimation = new My3dAnimation(ROTATE_X, 0, 180, centerX, centerY, 310f);
        }
        if (v.getId() == R.id.img_right) {
            my3dAnimation = new My3dAnimation(ROTATE_Y, 0, 180, centerX, centerY, 310f);
        }
        if (v.getId() == R.id.img_3) {
            centerX = 0;
            my3dAnimation = new My3dAnimation(ROTATE_Y, 0, 20, centerX, centerY, 310f);
        }

        my3dAnimation.setDuration(1000);
        my3dAnimation.setInterpolator(new LinearInterpolator());
        my3dAnimation.setFillAfter(true);
        v.startAnimation(my3dAnimation);
    }
}

三個按鈕示範了三種組合:img1 沿 X 軸翻轉 180 度、img2 沿 Y 軸翻轉 180 度、img3 則把 centerX 設為 0(關閉 Z 軸位移)並只轉 20 度。

setPersistentDrawingCache(PERSISTENT_ANIMATION_CACHE) 這行不可省。3D 動畫過程中 View 的繪製邊界會超出自身範圍,若容器沒有保留足夠的 drawing cache,旋轉中的內容會被裁切,看起來像被切掉一角。

LinearInterpolator 讓旋轉等速進行,這在 3D 翻轉場景中比加速減速更自然——真實物體的翻轉接近等速。setFillAfter(true) 讓動畫結束後停在最後一帧,不回彈。

三、進階方向

真正的翻牌效果需要兩個 View:正面轉到 90 度時切換顯示背面,背面從 -90 度轉到 0。這需要搭配 setAnimationListener 在 onAnimationEnd 時切換可見性。

改用 ObjectAnimator 更簡潔。Android 3.0 之後可以繼承更輕量的框架,或者直接使用 View 的 rotationX / rotationY 屬性搭配 cameraDistance 設定透視距離:

myView.setCameraDistance(8 * getResources().getDisplayMetrics().density);
myView.animate().rotationYBy(180f).setDuration(1000).start();

這段程式碼能做到與自定義 Animation 幾乎相同的效果,程式碼量卻少一個數量級。自定義 Camera + Matrix 的價值主要在於理解底層原理,以及實作那些內建屬性表達不了的複雜變換。

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