你應該看看培訓文檔Managing Bitmap Memory。根據您的操作系統版本,您可以使用不同的技術來管理更多的位圖,但您可能必須改變您的代碼。
特別是,你很可能將在「Load a Scaled Down Version into Memory」使用的代碼的修改版本,但我至少發現這部分特別有用:
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height/(float) reqHeight);
final int widthRatio = Math.round((float) width/(float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
這方法可以很容易地任意大尺寸 的位圖加載到一個顯示100×100像素的縮略圖的ImageView的,如在 所示的以下示例代碼:
mImageView.setImageBitmap(
decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));
我不同意將此標記爲重複。在這個問題中,同一個圖像被重複加載到一個循環中。即使圖像非常小,如果迭代次數足夠高,您會發現內存不足錯誤。 – britzl