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

Android 進階篇:自定義可縮放圖片控件 ZoomImageView 完整實作

編輯:關於 Android 程式設計

做圖片瀏覽器幾乎一定會遇到「雙指縮放、拖曳平移、雙擊放大」的需求。系統的 ImageView 只提供固定的 scaleType,要做得順手,就得自己寫一個。以下是一個以 Matrix 為核心的實作,思路清楚、效能可控。

設計思路:三個 Matrix 分工

整個控件由三個矩陣構成,各司其職:

mBaseMatrix 負責「初始狀態」——把圖片等比縮放到適合 View 的大小並置中。
mSuppMatrix 負責「使用者操作」——手勢造成的縮放與平移都疊在這裡。
mDisplayMatrix 是兩者相乘後的結果,也就是真正畫到畫布上的矩陣。

搭配兩個手勢偵測器:ScaleGestureDetector 處理雙指縮放,GestureDetector 處理拖曳、快速滑動與雙擊。兩者同時存在時,必須在縮放進行中停用拖曳,才不會互相打架。

核心程式碼

/**
 * 自定義可伸縮的 ImageView
 */
public class ZoomImageView extends View {

    private Paint mPaint;
    private Runnable mRefresh = null;

    /** 縮放手勢監聽 */
    private ScaleGestureDetector mScaleDetector;
    /** 手勢識別 */
    private GestureDetector mGestureDetector;

    /** 目前被渲染的 Bitmap */
    private Bitmap mBitmap;

    private int mThisWidth = -1, mThisHeight = -1;
    private Runnable mOnLayoutRunnable = null;

    private Matrix mBaseMatrix    = new Matrix();
    private Matrix mDisplayMatrix = new Matrix();
    private Matrix mSuppMatrix    = new Matrix();
    private Matrix mMatrix        = new Matrix();

    /** 最大拉伸比例 */
    private float mMaxZoom;
    private float[] mMatrixValues = new float[9];
    private Runnable mFling = null;

    private double mLastDraw = 0;
    static final int sPaintDelay = 250;

    public ZoomImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public ZoomImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ZoomImageView(Context context) {
        super(context);
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setDither(true);        // 圖像抖動處理
        mPaint.setFilterBitmap(true);  // 過濾優化,加快顯示
        mPaint.setAntiAlias(true);     // 去鋸齒

        /** 刷新 Runnable */
        mRefresh = new Runnable() {
            @Override
            public void run() {
                postInvalidate();
            }
        };

        mScaleDetector   = new ScaleGestureDetector(getContext(), new ScaleListener());
        mGestureDetector = new GestureDetector(getContext(), new MyGestureListener());

        // 判斷是否為新 API,開啟硬體加速
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }
    }

    public Bitmap getImageBitmap() {
        return mBitmap;
    }

    /** 回收 Bitmap */
    public void clear() {
        if (mBitmap != null && !mBitmap.isRecycled()) {
            mBitmap.recycle();
            mBitmap = null;
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        mThisWidth  = right - left;
        mThisHeight = bottom - top;

        Runnable r = mOnLayoutRunnable;
        if (r != null) {
            mOnLayoutRunnable = null;
            r.run();
        }

        if (mBitmap != null) {
            setBaseMatrix(mBitmap, mBaseMatrix);
            setImageMatrix(getImageViewMatrix());
        }
    }

    /** 計算初始矩陣:等比縮放並置中 */
    private void setBaseMatrix(Bitmap bitmap, Matrix matrix) {
        float viewWidth  = getWidth();
        float viewHeight = getHeight();

        matrix.reset();
        float widthScale  = Math.min(viewWidth  / (float) bitmap.getWidth(),  1.0f);
        float heightScale = Math.min(viewHeight / (float) bitmap.getHeight(), 1.0f);

        float scale = (widthScale > heightScale) ? heightScale : widthScale;

        matrix.setScale(scale, scale);
        matrix.postTranslate(
                (viewWidth  - ((float) bitmap.getWidth()  * scale)) / 2F,
                (viewHeight - ((float) bitmap.getHeight() * scale)) / 2F);
    }

    protected Matrix getImageViewMatrix() {
        mDisplayMatrix.set(mBaseMatrix);
        mDisplayMatrix.postConcat(mSuppMatrix);
        return mDisplayMatrix;
    }

    public void setImageMatrix(Matrix m) {
        // 單位矩陣視同 null
        if (m != null && m.isIdentity()) {
            m = null;
        }
        if ((m == null && !this.mMatrix.isIdentity())
                || (m != null && !this.mMatrix.equals(m))) {
            this.mMatrix.set(m);
            invalidate();
        }
    }

    static private void translatePoint(Matrix matrix, float[] xy) {
        matrix.mapPoints(xy);
    }

    /** 設定 Bitmap */
    public void setImageBitmap(final Bitmap bitmap) {
        final int viewWidth = getWidth();

        // 大圖關閉硬體加速,避免超過材質大小上限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB
                && bitmap != null && bitmap.getHeight() > 1800) {
            setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }

        if (viewWidth <= 0) {
            // 尚未完成佈局,等 onLayout 後再重試
            mOnLayoutRunnable = new Runnable() {
                public void run() {
                    setImageBitmap(bitmap);
                }
            };
            return;
        }

        if (bitmap != null) {
            setBaseMatrix(bitmap, mBaseMatrix);
            this.mBitmap = bitmap;
        } else {
            mBaseMatrix.reset();
            this.mBitmap = bitmap;
        }

        mSuppMatrix.reset();
        setImageMatrix(getImageViewMatrix());
        mMaxZoom = maxZoom();
        zoomTo(zoomDefault());
    }

    public void zoomTo(float scale) {
        zoomTo(scale, getWidth() / 2F, getHeight() / 2F);
    }

    /** 以指定中心點縮放 */
    protected void zoomTo(float scale, float centerX, float centerY) {
        if (scale > mMaxZoom) {
            scale = mMaxZoom;
        }

        float oldScale   = getScale();
        float deltaScale = scale / oldScale;

        mSuppMatrix.postScale(deltaScale, deltaScale, centerX, centerY);
        setImageMatrix(getImageViewMatrix());
        center(true, true, false);
    }

    /** 計算並修正中心位置,避免圖片被拖出邊界 */
    protected void center(boolean vertical, boolean horizontal, boolean animate) {
        if (mBitmap == null) {
            return;
        }

        Matrix m = getImageViewMatrix();

        float[] topLeft  = new float[] { 0, 0 };
        float[] botRight = new float[] { mBitmap.getWidth(), mBitmap.getHeight() };

        translatePoint(m, topLeft);
        translatePoint(m, botRight);

        float height = botRight[1] - topLeft[1];
        float width  = botRight[0] - topLeft[0];

        float deltaX = 0, deltaY = 0;

        if (vertical) {
            int viewHeight = getHeight();
            if (height < viewHeight) {
                deltaY = (viewHeight - height) / 2 - topLeft[1];
            } else if (topLeft[1] > 0) {
                deltaY = -topLeft[1];
            } else if (botRight[1] < viewHeight) {
                deltaY = getHeight() - botRight[1];
            }
        }

        if (horizontal) {
            int viewWidth = getWidth();
            if (width < viewWidth) {
                deltaX = (viewWidth - width) / 2 - topLeft[0];
            } else if (topLeft[0] > 0) {
                deltaX = -topLeft[0];
            } else if (botRight[0] < viewWidth) {
                deltaX = viewWidth - botRight[0];
            }
        }

        postTranslate(deltaX, deltaY);
        if (animate) {
            Animation a = new TranslateAnimation(-deltaX, 0, -deltaY, 0);
            a.setStartTime(SystemClock.elapsedRealtime());
            a.setDuration(250);
            setAnimation(a);
        }
        setImageMatrix(getImageViewMatrix());
    }

    protected void postTranslate(float dx, float dy) {
        mSuppMatrix.postTranslate(dx, dy);
    }

    public float getScale() {
        return getScale(mSuppMatrix);
    }

    protected float getScale(Matrix matrix) {
        return (mBitmap != null) ? getValue(matrix, Matrix.MSCALE_X) : 1f;
    }

    protected float getValue(Matrix matrix, int whichValue) {
        matrix.getValues(mMatrixValues);
        return mMatrixValues[whichValue];
    }

    /** 最大拉伸比例:圖片原始尺寸相對 View 的倍數,再放大 16 倍 */
    protected float maxZoom() {
        if (mBitmap == null) {
            return 1F;
        }
        float fw = (float) mBitmap.getWidth()  / (float) mThisWidth;
        float fh = (float) mBitmap.getHeight() / (float) mThisHeight;
        return Math.max(fw, fh) * 16;
    }

    /** 原始顯示比例 */
    public float zoomDefault() {
        if (mBitmap == null) {
            return 1F;
        }
        float fw = (float) mThisWidth  / (float) mBitmap.getWidth();
        float fh = (float) mThisHeight / (float) mBitmap.getHeight();
        return Math.max(Math.min(fw, fh), 1);
    }

    /** 帶時長的平滑縮放 */
    protected void zoomTo(final float scale, final float centerX,
                          final float centerY, final float durationMs) {
        final float incrementPerMs = (scale - getScale()) / durationMs;
        final float oldScale = getScale();
        final long startTime = System.currentTimeMillis();

        post(new Runnable() {
            public void run() {
                long now = System.currentTimeMillis();
                float currentMs = Math.min(durationMs, (float) (now - startTime));
                float target = oldScale + (incrementPerMs * currentMs);
                zoomTo(target, centerX, centerY);

                if (currentMs < durationMs) {
                    post(this);
                }
            }
        });
    }

    /** 快速滑動的緩動位移 */
    protected void scrollBy(float distanceX, float distanceY, final float durationMs) {
        final float dx = distanceX;
        final float dy = distanceY;
        final long startTime = System.currentTimeMillis();

        mFling = new Runnable() {
            float old_x = 0;
            float old_y = 0;

            public void run() {
                long now = System.currentTimeMillis();
                float currentMs = Math.min(durationMs, now - startTime);
                float x = easeOut(currentMs, 0, dx, durationMs);
                float y = easeOut(currentMs, 0, dy, durationMs);

                postTranslate((x - old_x), (y - old_y));
                center(true, true, false);

                old_x = x;
                old_y = y;
                if (currentMs < durationMs) {
                    post(this);
                }
            }
        };
        post(mFling);
    }

    private float easeOut(float time, float start, float end, float duration) {
        return end * ((time = time / duration - 1) * time * time + 1) + start;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mBitmap != null && !mBitmap.isRecycled()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB
                    && getLayerType() == View.LAYER_TYPE_HARDWARE) {
                canvas.drawBitmap(mBitmap, mMatrix, null);
            } else {
                // 軟體繪製時節流,避免縮放過程中過度重繪
                if ((System.currentTimeMillis() - mLastDraw) > sPaintDelay) {
                    canvas.drawBitmap(mBitmap, mMatrix, mPaint);
                    mLastDraw = System.currentTimeMillis();
                } else {
                    canvas.drawBitmap(mBitmap, mMatrix, null);
                    removeCallbacks(mRefresh);
                    postDelayed(mRefresh, sPaintDelay);
                }
            }
        }
    }

    /** 手勢縮放監聽 */
    class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            if (detector != null && detector.isInProgress()) {
                try {
                    float targetScale = getScale() * detector.getScaleFactor();
                    targetScale = Math.min(maxZoom(), Math.max(targetScale, 1.0f));
                    zoomTo(targetScale, detector.getFocusX(), detector.getFocusY());
                    invalidate();
                    return true;
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }
    }

    /** 手勢識別監聽 */
    class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {
            // 多點觸控或正在縮放時,不處理拖曳
            if ((e1 != null && e1.getPointerCount() > 1)
                    || (e2 != null && e2.getPointerCount() > 1)
                    || (mScaleDetector != null && mScaleDetector.isInProgress())) {
                return false;
            }

            if (getScale() > zoomDefault()) {
                removeCallbacks(mFling);
                postTranslate(-distanceX, -distanceY);
                center(true, true, false);
            }
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2,
                               float velocityX, float velocityY) {
            if ((e1 != null && e1.getPointerCount() > 1)
                    || (e2 != null && e2.getPointerCount() > 1)) {
                return false;
            }
            if (mScaleDetector.isInProgress()) {
                return false;
            }

            try {
                float diffX = e2.getX() - e1.getX();
                float diffY = e2.getY() - e1.getY();

                if (Math.abs(velocityX) > 800 || Math.abs(velocityY) > 800) {
                    scrollBy(diffX / 2, diffY / 2, 300);
                    invalidate();
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
            return super.onFling(e1, e2, velocityX, velocityY);
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            // 雙擊:已放大則還原,否則放大三倍
            if (getScale() > zoomDefault()) {
                zoomTo(zoomDefault());
            } else {
                zoomTo(zoomDefault() * 3, e.getX(), e.getY(), 200);
            }
            return true;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if (mImageTouchedListener != null) {
                mImageTouchedListener.onImageTouched();
                return false;
            }
            return super.onSingleTapConfirmed(e);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mBitmap != null) {
            mScaleDetector.onTouchEvent(event);
            if (!mScaleDetector.isInProgress()) {
                mGestureDetector.onTouchEvent(event);
            }
        }
        return true;
    }

    /** 點擊回呼 */
    private onImageTouchedListener mImageTouchedListener;

    public interface onImageTouchedListener {
        void onImageTouched();
    }

    public void setOnImageTouchedListener(onImageTouchedListener listener) {
        this.mImageTouchedListener = listener;
    }
}

版面檔

注意 scaleType 必須設為 matrix,才能讓自訂的 Matrix 生效:

<com.example.pay.ZoomImageView
    android:id="@+id/zommImageView"
    android:scaleType="matrix"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

在 Activity 中使用

mZoomImageView = (ZoomImageView) findViewById(R.id.zommImageView);
mZoomImageView.setImageBitmap(
        BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));

mZoomImageView.setOnImageTouchedListener(new onImageTouchedListener() {
    @Override
    public void onImageTouched() {
        Toast.makeText(MainActivity.this, "圖片被點擊", Toast.LENGTH_LONG).show();
    }
});

幾個實作上的提醒

大圖 (>=1800px) 一律切到軟體繪製,是因為硬體加速的材質有尺寸上限,超過會直接畫不出來;代價是效能下降,因此程式裡用 250ms 的節流避免每幀都重畫。center() 是體驗的關鍵——少了它,放大後很容易把圖片拖到螢幕外再也拉不回來。另外記得在頁面離開時呼叫 clear() 回收 Bitmap,否則大圖很容易造成 OOM。

如果只是想快速達到類似效果,也可以直接評估 PhotoView 這類成熟開源庫,它額外處理了 ViewPager 嵌套與手勢衝突等邊界情況。

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