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

Android 高清加載巨圖方案:告別圖片壓縮,輕鬆瀏覽清明上河圖

編輯:關於 Android 程式設計

一、前言

好久沒有更新文章了,最近忙於一些私事,今天就用一篇相對輕鬆的內容來重新找回手感。

說到加載圖片,相信每個 Android 開發者都不陌生。為了盡量避免 OOM(內存溢出),我們通常會採用兩種策略:其一,在展示圖片時,根據目標控件的實際尺寸對圖片進行等比壓縮,避免一次性把過大的位圖塞進內存;其二,當頁面中存在大量圖片時,引入 LruCache 這類緩存機制,把圖片占用的內存控制在一個合理的區間內。

然而,圖片加載還有一種頗為特殊的場景:單張圖片本身就非常巨大,而且業務上並不允許對它進行壓縮。典型例子包括世界地圖、清明上河圖、微博長圖等。這種情況下,我們又該如何應對呢?

仔細分析就會發現,如果不做壓縮、按照原始尺寸加載,屏幕根本放不下;考慮到內存限制,也不可能把整張大圖一次性讀進內存。因此唯一可行的思路是局部加載——只渲染當前屏幕可見的那一塊區域。為此,Android 提供了一個非常合適的類:BitmapRegionDecoder。

另外,既然屏幕一次顯示不完,起碼還得給用戶提供上下左右拖動的手勢,讓他們能夠自由瀏覽各個角落。

綜合以上兩點,本文的目標就是自定義一個能夠顯示巨圖的 View,支持手勢拖動查看,效果大致如下:

清明上河圖實在太長,如果想看完整全圖,可以在文末下載,圖片放在 assets 目錄裡。當然,如果你的圖片高度也很大,同樣可以上下拖動瀏覽。

二、初識 BitmapRegionDecoder

BitmapRegionDecoder 的核心能力,就是解碼並顯示圖片的某一塊矩形區域。當你只需要展示某張大圖的指定部分時,它堪稱量身定做。

它的用法相當直觀:既然只需要顯示一塊區域,那麼本質上就是「設置圖片」加「指定區域」兩步。先看構造對象的部分——BitmapRegionDecoder 提供了一系列 newInstance 方法,支持傳入文件路徑、文件描述符以及 InputStream 等多種數據源。

BitmapRegionDecoder bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);

這一步解決了「要處理哪張圖」的問題,接下來就是「顯示哪塊區域」。

bitmapRegionDecoder.decodeRegion(rect, options);

第一個參數是一個 Rect,用來描述要解碼的矩形範圍;第二個參數是 BitmapFactory.Options,通過它可以控制 inSampleSize、inPreferredConfig 等一系列選項。

下面是一個簡單到不能再簡單的示例:

package com.zhy.blogcodes.largeImage;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import com.zhy.blogcodes.R;
import java.io.IOException;
import java.io.InputStream;
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();
        }
    }
}

這段代碼從 assets 中打開圖片,通過 decodeRegion 解析出位於正中央的矩形區域並返回 Bitmap,最終顯示在 ImageView 上。

效果如下:

小圖顯示的正是下面那張大圖的中間區域。

掌握了 BitmapRegionDecoder 的基本用法後,我們要自定義一個顯示巨圖的控件就水到渠成了:本質上,那個 Rect 的範圍就是我們 View 的尺寸,而用戶拖動時,只需不斷更新 Rect 的參數即可。

三、自定義顯示大圖的控件

基於上面的分析,自定義控件的思路非常清晰:

提供一個設置圖片的入口;重寫 onTouchEvent,在其中根據用戶的移動手勢更新顯示區域的參數;每次更新後調用 invalidate,在 onDraw 裡通過 regionDecoder.decodeRegion 拿到對應的 Bitmap 並繪製。

理順之後發現其實並不難,直接上代碼:

package com.zhy.blogcodes.largeImage.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.io.IOException;
import java.io.InputStream;
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;
        int imageWidth = mImageWidth;
        if (rect.right > imageWidth) {
            rect.right = imageWidth;
            rect.left = imageWidth - getWidth();
        }
        if (rect.left < 0) {
            rect.left = 0;
            rect.right = getWidth();
        }
    }
    private void checkHeight() {
        Rect rect = mRect;
        int imageHeight = mImageHeight;
        if (rect.bottom > imageHeight) {
            rect.bottom = imageHeight;
            rect.top = imageHeight - 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();
        int imageWidth = mImageWidth;
        int imageHeight = mImageHeight;
        // 默認顯示圖片中心區域,可自行調整
        mRect.left = imageWidth / 2 - width / 2;
        mRect.top = imageHeight / 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 並繪製。

也許你會注意到,監聽 move 手勢的這段代碼寫得有點「特別」。這裡其實是模仿系統的 ScaleGestureDetector,自己實現了一個 MoveGestureDetector:

package com.zhy.blogcodes.largeImage.view;
import android.content.Context;
import android.graphics.PointF;
import android.view.MotionEvent;
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);
                boolean update = mListenter.onMove(this);
                if (update) {
                    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 {
        public boolean onMoveBegin(MoveGestureDetector detector);
        public boolean onMove(MoveGestureDetector detector);
        public 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) { }
    }
}

配套的抽象基類 BaseGestureDetector:

package com.zhy.blogcodes.largeImage.view;
import android.content.Context;
import android.view.MotionEvent;
public abstract class BaseGestureDetector {
    protected boolean mGestureInProgress;
    protected MotionEvent mPreMotionEvent;
    protected MotionEvent mCurrentMotionEvent;
    protected Context mContext;
    public BaseGestureDetector(Context context) {
        mContext = context;
    }
    public boolean onToucEvent(MotionEvent event) {
        if (!mGestureInProgress) {
            handleStartProgressEvent(event);
        } else {
            handleInProgressEvent(event);
        }
        return true;
    }
    protected abstract void handleInProgressEvent(MotionEvent event);
    protected abstract void handleStartProgressEvent(MotionEvent event);
    protected abstract void updateStateByEvent(MotionEvent event);
    protected void resetState() {
        if (mPreMotionEvent != null) {
            mPreMotionEvent.recycle();
            mPreMotionEvent = null;
        }
        if (mCurrentMotionEvent != null) {
            mCurrentMotionEvent.recycle();
            mCurrentMotionEvent = null;
        }
        mGestureInProgress = false;
    }
}

你可能會吐槽:一個 move 手勢用得著寫這麼多代碼嗎?確實,move 手勢的檢測本身很簡單。之所以如此設計,主要是為了可復用——當我們需要監聽各種手勢時,只要拿對應的 Detector 來檢測就行。相信不少人都暗自抱怨過 Google:為什麼只有 ScaleGestureDetector,卻沒有 RotateGestureDetector 呢?

值得一提的是,上面這套手勢檢測的寫法並非原創,而是借鑑自開源項目 https://github.com/rharter/android-gesture-detectors ,裡面積累了豐富的手勢檢測實現,對應的博文可參考 https://code.almeros.com/android-multitouch-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>

然後在 Activity 中設置圖片:

package com.zhy.blogcodes.largeImage;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.zhy.blogcodes.R;
import com.zhy.blogcodes.largeImage.view.LargeImageView;
import java.io.IOException;
import java.io.InputStream;
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 ,它幾乎實現了絕大多數常見需求。帶著本文的思路再去看這個庫,理解與定製都會輕鬆很多。本文用到的地圖素材,也正是來自這個項目。

掌握了這套方案,以後面試時也能悄悄「秀」一把:當你優雅地講完 Android 加載圖片的常規思路後,再補一句「其實還有一種場景,就是高清顯示巨圖,這時我們應該……」,相信面試官對你的印象會加分不少。祝你一切順利~

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