1. 程式人生 > >Android 如何實現大圖 不壓縮原樣載入

Android 如何實現大圖 不壓縮原樣載入

前言

由於圖片每個畫素點一般情況下,在android中會佔用4個位元組。對於一個1024*1024解析度的圖片就會佔用4MB記憶體,可見圖片對於記憶體的使用是非常大的,所以在Android系統中處理圖片基本上都會對其進行壓縮,比如設定取樣率,解析度等引數。
那麼如果有一張特別大的圖,如何不壓縮排行處理。其實也很簡單,可以使用 BitmapRegionDecoder。

原理

通過BitmapRegionDecoder 設定一個輸入流,然後動態的取區域性區域生成新的bitmap物件就可以了。貼下具體程式碼:

public class BigImageView extends android
.support.v7.widget.AppCompatImageView {
private BitmapRegionDecoder mBitmapRegionDecoder; private Bitmap mBitmap; private int mBitmapWidth, mBitmapHeight; private BitmapFactory.Options mOptions; private Rect mRect; public BigImageView(Context context) { super(context); } public
BigImageView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public BigImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } /** * 設定大圖輸入流 * * @param inputStream */
public void decodeInputStream(final InputStream inputStream) { post(new Runnable() { @Override public void run() { try { mBitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false); mBitmapWidth = mBitmapRegionDecoder.getWidth(); mBitmapHeight = mBitmapRegionDecoder.getHeight(); Log.d(BigImageView.class.getName(), mBitmapWidth + " " + mBitmapHeight); int left = 0, top = 0, right = 0, bottom = 0; if (getWidth() < mBitmapWidth) { right = getWidth(); } else { right = mBitmapWidth; } if (getHeight() < mBitmapHeight) { bottom = getHeight(); } else { bottom = mBitmapHeight; } mRect = new Rect(left, top, right, bottom); createRectBitmap(mRect); setImageBitmap(mBitmap); } catch (IOException e) { e.printStackTrace(); } } }); } private void createRectBitmap(Rect rect) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = false; options.inSampleSize=1; mBitmap = mBitmapRegionDecoder.decodeRegion(rect, options); } int mDownX = 0, mDownY; @Override public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getRawX(); int y = (int) event.getRawY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mDownX = x; mDownY = y; return true; case MotionEvent.ACTION_MOVE: int dx = mDownX - x; int dy = mDownY - y; if (getWidth() < mBitmapWidth) { mRect.left += dx; if (mRect.left < 0) mRect.left = 0; if (mRect.left > mBitmapWidth - getWidth()) mRect.left = mBitmapWidth - getWidth(); mRect.right = mRect.left + getWidth(); } if (getHeight() < mBitmapHeight) { mRect.top += dy; if (mRect.top < 0) mRect.top = 0; if (mRect.top > mBitmapHeight - getHeight()) mRect.top = mBitmapHeight - getHeight(); mRect.bottom = mRect.top + getHeight(); } createRectBitmap(mRect); setImageBitmap(mBitmap); mDownX = x; mDownY = y; break; } return super.onTouchEvent(event); } }

使用方法:bigImageView.decodeInputStream(assetManager.open(“t2.jpg”));