加载ImageView会导致OutOfMemory

时间:2013-07-11 18:24:44

标签: android imageview android-imageview out-of-memory

我有一个ImageView,我需要基于用户GPS位置的getImageResource()。 有6个图像,当2点之间的距离减少时,我用新资源替换图像。

我正在测试Galaxy S4上的应用程序,问题是在一个非常小的随机数量的加载后,应用程序因OutOfMemory而崩溃。

是否有一种缓存图像的好方法? (也许我需要使用AsyncTask加载它们)

图像为400x400px png-24位,具有透明度。

谢谢

2 个答案:

答案 0 :(得分:1)

尝试使用:

public static Bitmap decodeSampledBitmapFromResource(String uri,
        int reqWidth, int reqHeight, int orientation) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(uri, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    Bitmap decodeFile = BitmapFactory.decodeFile(uri, options);
    int rotate = 0;
    switch (orientation) {
    case ExifInterface.ORIENTATION_ROTATE_270:
        rotate = 270;
        break;
    case ExifInterface.ORIENTATION_ROTATE_180:
        rotate = 180;
        break;
    case ExifInterface.ORIENTATION_ROTATE_90:
        rotate = 90;
        break;
    }
    Matrix matrix = new Matrix();

    // matrix.postScale(scaleWidth, scaleHeight);
    matrix.postRotate(rotate);

    Bitmap rotatedBitmap = Bitmap.createBitmap(decodeFile, 0, 0,
            decodeFile.getWidth(), decodeFile.getHeight(), matrix, true);

    return rotatedBitmap;

}

private 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) {
        if (width > height) {
            inSampleSize = Math.round((float) height / (float) reqHeight);
        } else {
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }
    }
    return inSampleSize;
}

答案 1 :(得分:0)

Galaxy S4最有可能与xxhdpi drawable一起使用,因此您将所有内容放入mdpi将使系统放大图像以匹配S4的dpi级别,从而导致OutOfMemory错误。根据dpi(包括xhdpixxhdpi)尝试缩放并将drawable放在各自的文件夹中,之后可以优化代码。

相关问题