標籤:
BitmapFactory類提供了四類方法:decodeFile, decodeResource, decodeStream和decodeByteArray
分別用於支援從檔案系統,資源,輸入資料流以及位元組數組中載入出一個Bitmap對象,前兩者又間接調用了decodeStream
為了避免OOM,可以通過採樣率有效載入圖片
如果擷取採樣率?
1.將BitmapFactory.Options的inJustDecodeBounds的參數設定為true並載入圖片
2.從BitmapFactory.Options中取出圖片的原始寬高,它們對應outWidth和outHeight參數
3.根據採樣率的規則並結合目標View的所需大小計算採樣率inSampleSize
4.將BitmapFactory.Options的inJustDecodeBounds的參數設定為false,並重新載入圖片
上述步驟通過代碼體現:
public static Bitmap decodeSampledBitmapFromResource(Resource res, int resId, int reqWidth, int reqHeight){ final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options);}public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight){ final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if(height > reqHeight || width > reqWidth){ final int halfHeight = height / 2; final int halfWidth = width / 2; while((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth){ inSampleSize *= 2; } } return inSampleSize;}
Android開發之Bitmap的高效載入