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

Android 中軸旋轉特效:用 Camera 打造立體翻轉圖片瀏覽器

編輯:關於 Android 程式設計

Android API Demos 裡藏著不少寫得相當漂亮範例,值得逐一研究。本文就模仿其中一個 3D 變換效果,做出一個「列表翻轉變成圖片、點一下再翻回列表」的圖片瀏覽器。

為什麼選 Camera 而不是 OpenGL ES

在 Android 上要做 3D 有兩條路:OpenGL ES 與 Camera。前者功能強大但門檻高,通常用於遊戲或高階特效;若只是簡單的視圖翻轉,Camera 就綽綽有餘。

Camera 提供 rotateX()、rotateY()、rotateZ() 三個方法,傳入角度即可讓視圖繞該軸旋轉。中軸旋轉,本質上就是讓視圖繞 Y 軸轉動。

一、Rotate3dAnimation 工具類

/**
 * 讓視圖繞 Y 軸在兩個角度之間旋轉的動畫,
 * 並額外在 Z 軸(深度)方向做位移以強化立體感。
 */
public class Rotate3dAnimation extends Animation {

    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;

    public Rotate3dAnimation(float fromDegrees, float toDegrees,
                             float centerX, float centerY,
                             float depthZ, boolean reverse) {
        mFromDegrees = fromDegrees;
        mToDegrees = toDegrees;
        mCenterX = centerX;
        mCenterY = centerY;
        mDepthZ = depthZ;
        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) {
            camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
        } else {
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        }
        camera.rotateY(degrees);
        camera.getMatrix(matrix);
        camera.restore();

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

重點在 applyTransformation():

  1. 依動畫播放進度 interpolatedTime 算出當前角度。
  2. 讓 Camera 在 Z 軸上位移,製造「遠離視角」的景深感;mReverse 決定位移方向。
  3. 呼叫 rotateY() 完成 Y 軸旋轉。
  4. 以 preTranslate/postTranslate 組合把旋轉中心移到指定座標。

二、資料與適配器

public class Picture {
    private String name;    // 圖片名稱
    private int resource;   // 圖片資源 id

    public Picture(String name, int resource) {
        this.name = name;
        this.resource = resource;
    }

    public String getName()      { return name; }
    public int getResource()     { return resource; }
}
public class PictureAdapter extends ArrayAdapter<Picture> {

    public PictureAdapter(Context context, int textViewResourceId, List<Picture> objects) {
        super(context, textViewResourceId, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Picture picture = getItem(position);
        View view;
        if (convertView == null) {
            view = LayoutInflater.from(getContext())
                    .inflate(android.R.layout.simple_list_item_1, null);
        } else {
            view = convertView;
        }
        TextView text1 = (TextView) view.findViewById(android.R.id.text1);
        text1.setText(picture.getName());
        return view;
    }
}

三、主版面配置

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@+id/pic_list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitCenter"
        android:clickable="true"
        android:visibility="gone" />

</RelativeLayout>

ListView 與 ImageView 疊在同一個 RelativeLayout 中,透過切換 visibility 達到「翻面前後」的效果。

四、MainActivity 主流程

public class MainActivity extends Activity {

    private RelativeLayout layout;
    private ListView picListView;
    private ImageView picture;
    private PictureAdapter adapter;
    private List<Picture> picList = new ArrayList<>();

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

        initPics();

        layout = (RelativeLayout) findViewById(R.id.layout);
        picListView = (ListView) findViewById(R.id.pic_list_view);
        picture = (ImageView) findViewById(R.id.picture);

        adapter = new PictureAdapter(this, 0, picList);
        picListView.setAdapter(adapter);

        picListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                picture.setImageResource(picList.get(position).getResource());

                float centerX = layout.getWidth() / 2f;
                float centerY = layout.getHeight() / 2f;

                // 0 度 → 90 度:讓 ListView 從可見轉為不可見
                final Rotate3dAnimation rotation =
                        new Rotate3dAnimation(0, 90, centerX, centerY, 310.0f, true);
                rotation.setDuration(500);
                rotation.setFillAfter(true);
                rotation.setInterpolator(new AccelerateInterpolator());
                rotation.setAnimationListener(new TurnToImageView());
                layout.startAnimation(rotation);
            }
        });

        picture.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                float centerX = layout.getWidth() / 2f;
                float centerY = layout.getHeight() / 2f;

                // 360 度 → 270 度:反向轉回
                final Rotate3dAnimation rotation =
                        new Rotate3dAnimation(360, 270, centerX, centerY, 310.0f, true);
                rotation.setDuration(500);
                rotation.setFillAfter(true);
                rotation.setInterpolator(new AccelerateInterpolator());
                rotation.setAnimationListener(new TurnToListView());
                layout.startAnimation(rotation);
            }
        });
    }

    private void initPics() {
        picList.add(new Picture("Bird", R.drawable.bird));
        picList.add(new Picture("Winter", R.drawable.winter));
        picList.add(new Picture("Autumn", R.drawable.autumn));
        picList.add(new Picture("Great Wall", R.drawable.great_wall));
        picList.add(new Picture("Water Fall", R.drawable.water_fall));
    }

    /** ListView 動畫結束後,接著啟動 ImageView 的動畫 */
    class TurnToImageView implements AnimationListener {

        @Override public void onAnimationStart(Animation animation) { }

        @Override
        public void onAnimationEnd(Animation animation) {
            float centerX = layout.getWidth() / 2f;
            float centerY = layout.getHeight() / 2f;

            picListView.setVisibility(View.GONE);
            picture.setVisibility(View.VISIBLE);
            picture.requestFocus();

            // 270 度 → 360 度:讓 ImageView 從不可見轉為可見
            final Rotate3dAnimation rotation =
                    new Rotate3dAnimation(270, 360, centerX, centerY, 310.0f, false);
            rotation.setDuration(500);
            rotation.setFillAfter(true);
            rotation.setInterpolator(new AccelerateInterpolator());
            layout.startAnimation(rotation);
        }

        @Override public void onAnimationRepeat(Animation animation) { }
    }

    /** ImageView 動畫結束後,接著啟動 ListView 的動畫 */
    class TurnToListView implements AnimationListener {

        @Override public void onAnimationStart(Animation animation) { }

        @Override
        public void onAnimationEnd(Animation animation) {
            float centerX = layout.getWidth() / 2f;
            float centerY = layout.getHeight() / 2f;

            picture.setVisibility(View.GONE);
            picListView.setVisibility(View.VISIBLE);
            picListView.requestFocus();

            // 90 度 → 0 度:回到原點
            final Rotate3dAnimation rotation =
                    new Rotate3dAnimation(90, 0, centerX, centerY, 310.0f, false);
            rotation.setDuration(500);
            rotation.setFillAfter(true);
            rotation.setInterpolator(new AccelerateInterpolator());
            layout.startAnimation(rotation);
        }

        @Override public void onAnimationRepeat(Animation animation) { }
    }
}

執行流程梳理

點擊列表項時,先把 ImageView 的圖換成被點的那張,算出版面中心作為旋轉軸,然後啟動 0°→90° 的動畫並掛上 TurnToImageView。動畫結束後在回呼中把 ListView 設為 GONE、ImageView 設為 VISIBLE,再跑 270°→360°,視覺上就形成「列表沿中軸翻走、圖片沿中軸翻入」的連貫效果。

反向流程同理:先讓 ImageView 從 360° 轉到 270°(確保方向與進入時相反),結束後切換可見性,再讓 ListView 從 90° 轉回 0°。

關鍵設計觀念

這個範例最值得學的不是動畫本身,而是用 AnimationListener 把兩段動畫串成序列的技巧。任何需要「A 做完接著做 B」的動畫,都可以用這個模式處理。另外注意角度的選擇:進入用 0→90,出現用 270→360,兩者相加為 360 度,如此翻入與翻出的方向才會一致而不突兀。

若要在新專案實作,建議改用 ViewPropertyAnimator 搭配 rotationY 與 cameraDistance,或使用 ViewFlipper 與 TransitionManager,能少寫很多樣板程式碼,也更容易維護。

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