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

Android 高清加載長圖與大圖的實戰方案

編輯:關於 Android 程式設計

一、問題背景

談到載入圖片,為避免 OOM,一般做法有兩種:顯示時依控制項大小對圖片進行壓縮;圖片數量龐大時則採用 LruCache 等快取機制,把總佔用量維持在可控範圍。

但還有一類特殊場景:單張圖片極為巨大,而且不允許壓縮,例如世界地圖、清明上河圖、微博長圖等。這時该怎么办?

既然不壓縮、要依原圖尺寸載入,螢幕肯定容不下整張圖,加上記憶體考量,也不可能一次把整圖塞進記憶體,因此只能「局部載入」,這就需要用到 BitmapRegionDecoder。此外,既然畫面顯示不完,至少得加上上下左右拖動的手勢,讓使用者能滑動瀏覽。

本文的目標,就是自訂一個能顯示巨圖、支援拖動查看的 View。效果如下:

這張清明上河圖相當長,若要觀看全圖可於文末下載(圖片位於 assets 目錄);若你的圖高度也很大,同樣可以上下拖動。

二、初識 BitmapRegionDecoder

BitmapRegionDecoder 主要用於顯示圖片的某一塊矩形區域,非常適合需要顯示指定區域的場合。用法很簡單:一組 newInstance 方法負責載入圖片(支援傳入檔案路徑、檔案描述符、InputStream 等),再用 decodeRegion() 解析指定區域。

BitmapRegionDecoder bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
bitmapRegionDecoder.decodeRegion(rect, options);

參數一 rect 是欲顯示的矩形區域,參數二 BitmapFactory.Options 可控制 inSampleSize、inPreferredConfig 等。以下是一個極簡範例,載入 assets 圖片並解析中央矩形區域:

public class LargeImageViewActivity extends AppCompatActivity {
    private ImageView mImageView;
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_large_image_view);
        mImageView = (ImageView) findViewById(R.id.id_imageview);
        try {
            InputStream inputStream = getAssets().open("tangyan.jpg");
            // 先取得圖片的寬高
            BitmapFactory.Options tmpOptions = new BitmapFactory.Options();
            tmpOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(inputStream, null, tmpOptions);
            int width = tmpOptions.outWidth;
            int height = tmpOptions.outHeight;
            // 解析中央區域
            BitmapRegionDecoder bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            Bitmap bitmap = bitmapRegionDecoder.decodeRegion(
                new Rect(width / 2 - 100, height / 2 - 100, width / 2 + 100, height / 2 + 100), options);
            mImageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

效果圖:

小圖顯示的正是大圖的中央區域。理解了 BitmapRegionDecoder 的基本用法後,自訂一個顯示巨圖的控制項就順理成章:讓 Rect 的範圍等於 View 的大小,再依使用者手勢不斷更新 Rect 參數即可。

三、自訂顯示大圖控制項

思路非常清晰:

· 提供一個設定圖片的入口;
· 重寫 onTouchEvent,依移動手勢更新顯示區域參數;
· 每次更新後呼叫 invalidate,在 onDraw 中以 decodeRegion 取得 bitmap 並繪製。

public class LargeImageView extends View {
    private BitmapRegionDecoder mDecoder;
    private int mImageWidth, mImageHeight;
    private volatile Rect mRect = new Rect();
    private MoveGestureDetector mDetector;
    private static final BitmapFactory.Options options = new BitmapFactory.Options();
    static {
        options.inPreferredConfig = Bitmap.Config.RGB_565;
    }
    public void setInputStream(InputStream is) {
        try {
            mDecoder = BitmapRegionDecoder.newInstance(is, false);
            BitmapFactory.Options tmpOptions = new BitmapFactory.Options();
            tmpOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(is, null, tmpOptions);
            mImageWidth = tmpOptions.outWidth;
            mImageHeight = tmpOptions.outHeight;
            requestLayout();
            invalidate();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try { if (is != null) is.close(); } catch (Exception e) { }
        }
    }
    public void init() {
        mDetector = new MoveGestureDetector(getContext(), new MoveGestureDetector.SimpleMoveGestureDetector() {
            @Override public boolean onMove(MoveGestureDetector detector) {
                int moveX = (int) detector.getMoveX();
                int moveY = (int) detector.getMoveY();
                if (mImageWidth > getWidth()) {
                    mRect.offset(-moveX, 0);
                    checkWidth();
                    invalidate();
                }
                if (mImageHeight > getHeight()) {
                    mRect.offset(0, -moveY);
                    checkHeight();
                    invalidate();
                }
                return true;
            }
        });
    }
    private void checkWidth() {
        Rect rect = mRect;
        if (rect.right > mImageWidth) {
            rect.right = mImageWidth;
            rect.left = mImageWidth - getWidth();
        }
        if (rect.left < 0) {
            rect.left = 0;
            rect.right = getWidth();
        }
    }
    private void checkHeight() {
        Rect rect = mRect;
        if (rect.bottom > mImageHeight) {
            rect.bottom = mImageHeight;
            rect.top = mImageHeight - getHeight();
        }
        if (rect.top < 0) {
            rect.top = 0;
            rect.bottom = getHeight();
        }
    }
    public LargeImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    @Override public boolean onTouchEvent(MotionEvent event) {
        mDetector.onToucEvent(event);
        return true;
    }
    @Override protected void onDraw(Canvas canvas) {
        Bitmap bm = mDecoder.decodeRegion(mRect, options);
        canvas.drawBitmap(bm, 0, 0, null);
    }
    @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        // 預設顯示圖片中央區域
        mRect.left = mImageWidth / 2 - width / 2;
        mRect.top = mImageHeight / 2 - height / 2;
        mRect.right = mRect.left + width;
        mRect.bottom = mRect.top + height;
    }
}

重點整理:setInputStream 取得圖片真實寬高並初始化 mDecoder;onMeasure 為顯示區域 Rect 賦值(大小為 View 尺寸);onTouchEvent 監聽 move 手勢、改變 Rect 並做邊界檢查、最後 invalidate;onDraw 依 Rect 取 bitmap 繪製。

你或許會覺得手勢監聽的寫法有點奇怪——這是仿照系統的 ScaleGestureDetector,自訂了 MoveGestureDetector。之所以如此包裝,是為了復用:當需要監聽各種手勢時,直接取一個對應的 detector 即可。相信不少人也曾納悶,Google 為何只有 ScaleGestureDetector 卻沒有 RotateGestureDetector。

MoveGestureDetector 與其基底 BaseGestureDetector 的實作如下(此寫法取自開源專案 android-gesture-detectors):

public class MoveGestureDetector extends BaseGestureDetector {
    private PointF mCurrentPointer;
    private PointF mPrePointer;
    private PointF mDeltaPointer = new PointF();
    private PointF mExtenalPointer = new PointF();
    private OnMoveGestureListener mListenter;

    public MoveGestureDetector(Context context, OnMoveGestureListener listener) {
        super(context);
        mListenter = listener;
    }
    @Override protected void handleInProgressEvent(MotionEvent event) {
        int actionCode = event.getAction() & MotionEvent.ACTION_MASK;
        switch (actionCode) {
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                mListenter.onMoveEnd(this);
                resetState();
                break;
            case MotionEvent.ACTION_MOVE:
                updateStateByEvent(event);
                if (mListenter.onMove(this)) {
                    mPreMotionEvent.recycle();
                    mPreMotionEvent = MotionEvent.obtain(event);
                }
                break;
        }
    }
    @Override protected void handleStartProgressEvent(MotionEvent event) {
        int actionCode = event.getAction() & MotionEvent.ACTION_MASK;
        switch (actionCode) {
            case MotionEvent.ACTION_DOWN:
                resetState();
                mPreMotionEvent = MotionEvent.obtain(event);
                updateStateByEvent(event);
                break;
            case MotionEvent.ACTION_MOVE:
                mGestureInProgress = mListenter.onMoveBegin(this);
                break;
        }
    }
    protected void updateStateByEvent(MotionEvent event) {
        final MotionEvent prev = mPreMotionEvent;
        mPrePointer = caculateFocalPointer(prev);
        mCurrentPointer = caculateFocalPointer(event);
        boolean mSkipThisMoveEvent = prev.getPointerCount() != event.getPointerCount();
        mExtenalPointer.x = mSkipThisMoveEvent ? 0 : mCurrentPointer.x - mPrePointer.x;
        mExtenalPointer.y = mSkipThisMoveEvent ? 0 : mCurrentPointer.y - mPrePointer.y;
    }
    private PointF caculateFocalPointer(MotionEvent event) {
        final int count = event.getPointerCount();
        float x = 0, y = 0;
        for (int i = 0; i < count; i++) {
            x += event.getX(i);
            y += event.getY(i);
        }
        x /= count;
        y /= count;
        return new PointF(x, y);
    }
    public float getMoveX() { return mExtenalPointer.x; }
    public float getMoveY() { return mExtenalPointer.y; }

    public interface OnMoveGestureListener {
        boolean onMoveBegin(MoveGestureDetector detector);
        boolean onMove(MoveGestureDetector detector);
        void onMoveEnd(MoveGestureDetector detector);
    }
    public static class SimpleMoveGestureDetector implements OnMoveGestureListener {
        @Override public boolean onMoveBegin(MoveGestureDetector detector) { return true; }
        @Override public boolean onMove(MoveGestureDetector detector) { return false; }
        @Override public void onMoveEnd(MoveGestureDetector detector) { }
    }
}

這樣包裝的好處是:手勢檢測的骨架可跨手勢復用,日後要新增各種 XXXGestureDetector 都輕而易舉。上述兩個類靈感來自開源專案 https://github.com/rharter/android-gesture-detectors。

四、測試

把 LargeImageView 放入布局檔,並在 Activity 中設定 inputstream 即可:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.zhy.blogcodes.largeImage.view.LargeImageView
        android:id="@+id/id_largetImageview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>
public class LargeImageViewActivity extends AppCompatActivity {
    private LargeImageView mLargeImageView;
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_large_image_view);
        mLargeImageView = (LargeImageView) findViewById(R.id.id_largetImageview);
        try {
            InputStream inputStream = getAssets().open("world.jpg");
            mLargeImageView.setInputStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

效果圖:

至此,顯示巨圖的方案與完整程式碼便告一段落,整體並不複雜。實際專案中若有更多需求,例如縮放、快滑手勢等,可參考開源庫 https://github.com/johnnylambada/WorldMap,它幾乎實作了絕大多數常見需求。以本文的思路去閱讀該庫,理解與定製都會輕鬆許多。

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