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

把 Gallery 改造成 Coverflow:GalleryFlow 的 3D 相簿牆實作

編輯:關於 Android 程式設計

標準的 Gallery 是平坦地橫向捲動,而 Coverflow 那種「中間放大、兩側往後傾斜」的 3D 相簿牆,其實可以靠繼承 Gallery 並覆寫一個方法就做出來。整個效果由三個部分組成:自訂 GalleryFlow、負責產生倒影的 ImageAdapter,以及把它們組起來的 Activity。

一、GalleryFlow:讓每張圖各自旋轉與縮放

關鍵是 setStaticTransformationsEnabled(true)——開啟之後,Gallery 在配置子 View 時就會呼叫 getChildStaticTransformation(),我們在裡面依「這個子 View 距中心的偏移」決定它的旋轉角度與縮放量。

public class GalleryFlow extends Gallery {

    private Camera mCamera = new Camera();      // 負責透視變換
    private int mMaxRotationAngle = 60;         // 最大旋轉角度
    private int mMaxZoom = -300;                // 最大縮放量
    private int mCoveflowCenter;                // 容器中心(半徑)

    public GalleryFlow(Context context) {
        super(context);
        this.setStaticTransformationsEnabled(true);   // 啟用轉換
    }

    public GalleryFlow(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setStaticTransformationsEnabled(true);
    }

    public GalleryFlow(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.setStaticTransformationsEnabled(true);
    }

    private int getCenterOfCoverflow() {
        return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft();
    }

    private static int getCenterOfView(View view) {
        return view.getLeft() + view.getWidth() / 2;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        mCoveflowCenter = getCenterOfCoverflow();
        super.onSizeChanged(w, h, oldw, oldh);
    }

    // 控制 Gallery 中每張圖片的旋轉
    @Override
    protected boolean getChildStaticTransformation(View child, Transformation t) {
        final int childCenter = getCenterOfView(child);
        final int childWidth = child.getWidth();

        int rotationAngle = 0;
        t.clear();
        t.setTransformationType(Transformation.TYPE_MATRIX);

        if (childCenter == mCoveflowCenter) {
            transformImageBitmap((ImageView) child, t, 0);   // 正中間不旋轉
        } else {
            // 依距離中心的偏移比例換算角度
            rotationAngle = (int) (((float) (mCoveflowCenter - childCenter)
                                    / childWidth) * mMaxRotationAngle);
            // 超過上限就夾住
            if (Math.abs(rotationAngle) > mMaxRotationAngle) {
                rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle : mMaxRotationAngle;
            }
            transformImageBitmap((ImageView) child, t, rotationAngle);
        }
        return true;
    }

    private void transformImageBitmap(ImageView child, Transformation t, int rotationAngle) {
        mCamera.save();
        final Matrix imageMatrix = t.getMatrix();
        final int imageHeight = child.getLayoutParams().height;
        final int imageWidth = child.getLayoutParams().width;
        final int rotation = Math.abs(rotationAngle);

        // Z 軸正向移動 = 把視角拉遠(圖片變小)
        mCamera.translate(0.0f, 0.0f, 100.0f);

        // 角度越接近中間,就放大一點,做出「往前凸」的感覺
        if (rotation < mMaxRotationAngle) {
            float zoomAmount = (float) (mMaxZoom + (rotation * 1.5));
            mCamera.translate(0.0f, 0.0f, zoomAmount);
        }

        mCamera.rotateY(rotationAngle);      // 繞 Y 軸旋轉 = 向內翻
        mCamera.getMatrix(imageMatrix);

        // 以圖片中心為軸心
        imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
        imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));

        mCamera.restore();
    }
}

Camera 的三個軸向要記牢:Z 軸位移對應放大縮小,Y 軸旋轉對應「上下邊往內翻」,X 軸旋轉則是「左右邊往內翻」。Coverflow 用的是 Y 軸。

二、ImageAdapter:把倒影畫進 Bitmap

倒影不是另一個 View,而是直接在 createReflectedImages() 裡把「原圖 + 倒影」合成一張新的 Bitmap,順便套上漸層遮罩讓倒影自然淡出。

public class ImageAdapter extends BaseAdapter {

    private Context mContext;
    private Integer[] mImageIds;
    private ImageView[] mImages;

    public ImageAdapter(Context c, Integer[] ImageIds) {
        mContext = c;
        mImageIds = ImageIds;
        mImages = new ImageView[mImageIds.length];
    }

    /** 建立倒影效果 */
    public boolean createReflectedImages() {
        final int reflectionGap = 4;      // 原圖與倒影間距
        int index = 0;

        for (int imageId : mImageIds) {
            Bitmap originalImage =
                BitmapFactory.decodeResource(mContext.getResources(), imageId);
            int width = originalImage.getWidth();
            int height = originalImage.getHeight();

            // Y 軸反轉,做出鏡像
            Matrix matrix = new Matrix();
            matrix.preScale(1, -1);
            Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
                    height / 2, width, height / 2, matrix, false);

            // 組合畫布:高度 = 原圖 + 倒影
            Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
                    (height + height / 2), Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmapWithReflection);
            canvas.drawBitmap(originalImage, 0, 0, null);
            canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

            // 用 LinearGradient + DST_IN 讓倒影上淡下深
            Paint paint = new Paint();
            paint.setAntiAlias(false);
            LinearGradient shader = new LinearGradient(0, originalImage.getHeight(),
                    0, bitmapWithReflection.getHeight() + reflectionGap,
                    0x70ffffff, 0x00ffffff, TileMode.MIRROR);
            paint.setShader(shader);
            paint.setXfermode(new PorterDuffXfermode(
                    android.graphics.PorterDuff.Mode.DST_IN));
            canvas.drawRect(0, height, width,
                    bitmapWithReflection.getHeight() + reflectionGap, paint);

            ImageView imageView = new ImageView(mContext);
            imageView.setImageBitmap(bitmapWithReflection);
            imageView.setLayoutParams(new GalleryFlow.LayoutParams(300, 400));
            mImages[index++] = imageView;
        }
        return true;
    }

    @Override public int getCount() { return mImageIds.length; }
    @Override public Object getItem(int position) { return position; }
    @Override public long getItemId(int position) { return position; }
    @Override public View getView(int position, View convertView, ViewGroup parent) {
        return mImages[position];
    }
}

這裡有個值得理解的細節:PorterDuff.Mode.DST_IN 代表「保留目標圖像與來源圖像交集處,並以來源的不透明度相乘」。搭配一個從 0x70ffffff(半透明白)漸變到 0x00ffffff(全透明)的 LinearGradient,倒影下半部就被逐渐削去,看起來像消失在水面。這比手動逐列調整 alpha 簡潔得多。

三、Activity:把它們組裝起來

public class Gallery3DActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_gallery);

        Integer[] images = {
            R.drawable.img0001, R.drawable.img0030,
            R.drawable.img0100, R.drawable.img0130,
            R.drawable.img0200, R.drawable.img0230,
            R.drawable.img0330, R.drawable.img0354
        };

        ImageAdapter adapter = new ImageAdapter(this, images);
        adapter.createReflectedImages();                    // 先產生倒影

        GalleryFlow galleryFlow = (GalleryFlow) findViewById(R.id.Gallery01);
        galleryFlow.setFadingEdgeLength(0);
        galleryFlow.setSpacing(-100);                       // 負值讓圖片互相重疊
        galleryFlow.setAdapter(adapter);

        galleryFlow.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Toast.makeText(getApplicationContext(),
                        String.valueOf(position), Toast.LENGTH_SHORT).show();
            }
        });

        galleryFlow.setSelection(4);                        // 預設停在第 5 張
    }
}

setSpacing(-100) 是 Coverflow 觀感的另一半:負間距讓相鄰圖片彼此重疊,配合旋轉才會產生「一疊卡片」的層次。

寫完之後,該知道的事

這份程式有明確的時代記號:Gallery 在 API 14 就被標記為 deprecated,官方建議改用 HorizontalScrollView 或 RecyclerView 自行實作。原因是 Gallery 對鍵盤、D-pad 與無障礙操作的支援有先天限制。

不過裡面的數學與 Camera 用法完全沒有過時。今天的做法是把同樣的邏輯搬到 RecyclerView.LayoutManager 上——覆寫 scrollVerticallyBy() 攔下捲動位移,再對每個可見子 View 依它與中心的距離呼叫 setTranslationZ() 與 setRotationY()。API 21 之後甚至不必再用 Camera,直接給 View 加上 setCameraDistance() 就能得到透視感。

另外,倒影那段的 Bitmap.createBitmap() 會為每張圖配置三份記憶體(原圖、倒影、合成圖)。清單一大就會有壓力,實作時應在 Activity 銷毀時 recycle,或改用 RenderScriptEffect / RenderEffect 在 GPU 上完成,成本會低很多。

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