Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

用 Camera 實現中軸翻轉:手把手寫一個 3D 圖片瀏覽器

編輯:Android 開發實例

Android 自帶的 API Demos 裡藏著不少好東西,代碼質量頗高。把裡面的示例一個個啃透,功力自然會長上一大截——對不少還在摸索方向的開發者來說,這其實是一條相當踏實的成長路徑。

今天我們就挑其中一個 3D 變換特效下手,做一個別開生面的圖片瀏覽器。

選 Camera 還是 OpenGL ES

既然要做中軸旋轉,就離不開 3D 變換。Android 上做 3D 大致有兩條路:一是 OpenGL ES,二是 Camera。

OpenGL ES 強大但笨重,通常用在比較高級的 3D 特效或者遊戲裡。而像中軸旋轉這種量級的效果,用 Camera 就綽綽有餘,代碼量也友好得多。

Camera 提供了三個旋轉方法:rotateX()、rotateY() 和 rotateZ(),分別對應三根軸。傳入角度,視圖就會繞該軸旋轉。我們這次要的中軸旋轉,本質上就是讓視圖繞 Y 軸翻過去。

新建項目 RotatePicBrowserDemo,準備幾張測試圖片,開始。

第一步:把 Rotate3dAnimation 搬進項目

API Demos 已經給我們準備了一個很好用的工具類 Rotate3dAnimation,它本身就是基於 Camera 實現的。先把這個類複製到項目裡:

/**
 * An animation that rotates the view on the Y axis between two specified angles.
 * This animation also adds a translation on the Z axis (depth) to improve the effect.
 */
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;

    /**
     * Creates a new 3D rotation on the Y axis.
     *
     * @param fromDegrees the start angle of the 3D rotation
     * @param toDegrees the end angle of the 3D rotation
     * @param centerX the X center of the 3D rotation
     * @param centerY the Y center of the 3D rotation
     * @param reverse true if the translation should be reversed, false otherwise
     */
    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);
    }
}

構造函數接收 3D 旋轉所需的參數:起止角度、旋轉中心、Z 軸深度以及是否反向平移。

真正的重頭戲是 applyTransformation()。它先用 interpolatedTime(動畫當前播放的百分比)在起止角度之間做插值,算出此刻該轉到多少度;接著讓 Camera 沿 Z 軸做一段平移,製造出「正在遠離視角」的縱深感,mReverse 決定這段平移是正向還是反向;然後 rotateY() 完成真正的翻轉,getMatrix() 把變換矩陣取出來;最後用一對 pre/postTranslate 把旋轉中心校正到指定位置。

有了這個工具類,中軸旋轉就變成一件很省心的事。

第二步:Picture 實體類與適配器

public class Picture {

    /**
     * 圖片名稱
     */
    private String name;

    /**
     * 圖片對象的資源
     */
    private int resource;

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

    public String getName() {
        return name;
    }

    public int getResource() {
        return resource;
    }

}

只有兩個字段:name 用於列表展示,resource 指向對應的圖片資源。

接著寫列表適配器,讓 ListView 能顯示一組圖片名稱:

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;
    }

}

第三步:主布局

打開或新建 activity_main.xml:

<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"
        >
    </ListView>

    <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 用來展示大圖。注意 ImageView 初始是 gone——它要等中軸旋轉的那一瞬間才登場。

第四步:MainActivity 的翻轉邏輯

public class MainActivity extends Activity {

    /**
     * 根布局
     */
    private RelativeLayout layout;

    /**
     * 用於展示圖片列表的 ListView
     */
    private ListView picListView;

    /**
     * 用於展示圖片詳細的 ImageView
     */
    private ImageView picture;

    /**
     * 圖片列表的適配器
     */
    private PictureAdapter adapter;

    /**
     * 存放所有圖片的集合
     */
    private List<Picture> picList = new ArrayList<Picture>();

    @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) {
                // 當點擊某一子項時,將 ImageView 中的圖片設置為相應的資源
                picture.setImageResource(picList.get(position).getResource());
                // 獲取布局的中心點位置,作為旋轉的中心點
                float centerX = layout.getWidth() / 2f;
                float centerY = layout.getHeight() / 2f;
                // 構建 3D 旋轉動畫對象,旋轉角度為 0 到 90 度
                final Rotate3dAnimation rotation = new Rotate3dAnimation(0, 90, centerX, centerY,
                        310.0f, true);
                // 動畫持續時間 500 毫秒
                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;
                // 構建 3D 旋轉動畫對象,旋轉角度為 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() {
        Picture bird = new Picture("Bird", R.drawable.bird);
        picList.add(bird);
        Picture winter = new Picture("Winter", R.drawable.winter);
        picList.add(winter);
        Picture autumn = new Picture("Autumn", R.drawable.autumn);
        picList.add(autumn);
        Picture greatWall = new Picture("Great Wall", R.drawable.great_wall);
        picList.add(greatWall);
        Picture waterFall = new Picture("Water Fall", R.drawable.water_fall);
        picList.add(waterFall);
    }

    /**
     * 注冊在 ListView 點擊動畫中的動畫監聽器,用於完成 ListView 的後續動畫。
     */
    class TurnToImageView implements AnimationListener {

        @Override
        public void onAnimationStart(Animation animation) {
        }

        /**
         * 當 ListView 的動畫完成後,還需要再啟動 ImageView 的動畫,讓 ImageView 從不可見變為可見
         */
        @Override
        public void onAnimationEnd(Animation animation) {
            // 獲取布局的中心點位置,作為旋轉的中心點
            float centerX = layout.getWidth() / 2f;
            float centerY = layout.getHeight() / 2f;
            // 將 ListView 隱藏
            picListView.setVisibility(View.GONE);
            // 將 ImageView 顯示
            picture.setVisibility(View.VISIBLE);
            picture.requestFocus();
            // 構建 3D 旋轉動畫對象,旋轉角度為 270 到 360 度
            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 點擊動畫中的動畫監聽器,用於完成 ImageView 的後續動畫。
     */
    class TurnToListView implements AnimationListener {

        @Override
        public void onAnimationStart(Animation animation) {
        }

        /**
         * 當 ImageView 的動畫完成後,還需要再啟動 ListView 的動畫,讓 ListView 從不可見變為可見
         */
        @Override
        public void onAnimationEnd(Animation animation) {
            // 獲取布局的中心點位置,作為旋轉的中心點
            float centerX = layout.getWidth() / 2f;
            float centerY = layout.getHeight() / 2f;
            // 將 ImageView 隱藏
            picture.setVisibility(View.GONE);
            // 將 ListView 顯示
            picListView.setVisibility(View.VISIBLE);
            picListView.requestFocus();
            // 構建 3D 旋轉動畫對象,旋轉角度為 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) {
        }

    }

}

代碼註釋寫得夠細,這裡只把執行流程串一遍。

onCreate() 先調 initPics() 準備數據,拿到各控件實例並讓列表顯示出來,然後分別給 ListView 和 ImageView 掛上點擊事件。

點擊列表項時:先把 ImageView 的圖換成對應資源,再算出整個布局的中心點作為旋轉中心,然後啟動一段 0 度到 90 度的 Rotate3dAnimation,同時掛上 TurnToImageView 監聽器。動畫播完,TurnToImageView 在 onAnimationEnd 裡把 ListView 設為 GONE、ImageView 設為 VISIBLE,接著立刻補一段 270 度到 360 度的旋轉。於是視覺上就連貫起來了:列表繞中軸轉沒,圖片接著繞中軸轉出來。

點擊 ImageView 時是鏡像流程:先讓它從 360 度轉到 270 度(保證是往反方向轉回去),再由 TurnToListView 在動畫結束後切換可見性,最後把 ListView 從 90 度轉回 0 度,完成一次完整的往返。

這裡有個容易忽略的細節:兩段動畫之所以能無縫銜接,靠的是 setFillAfter(true) 加上精確的角度銜接——前一段停在 90 度,後一段就從 90 度出發;切換可見性恰好發生在視圖「側身」看不見的那一瞬間,穿幫的機會自然是零。

全部代碼完成,跑起來看看:在名稱列表裡點一項,畫面中軸翻轉到對應圖片;再點圖片,又中軸翻轉回列表。

效果還是相當不錯的。本文的主要代碼其實都來自 API Demos,原創比例並不高——但這恰恰是重點:學會 Camera 的用法之後,下一篇我們就要用它做出更炫更酷的東西了。

源碼下載,請點擊這裡

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