【问题标题】:Loading ImageView causes OutOfMemory加载 ImageView 导致 OutOfMemory
【发布时间】:2013-07-12 03:05:29
【问题描述】:

我有一个 ImageView,我需要根据用户 GPS 位置获取图像资源()。 有 6 张图像,随着 2 点之间的距离减小,我将图像替换为新资源。

我正在 Galaxy S4 上测试该应用程序,问题是在非常小的随机加载次数后,该应用程序由于 OutOfMemory 而崩溃。

有没有缓存图片的好方法? (也许我需要使用 AsyncTask 加载它们)

图片为 400x400px png- 24 位透明。

谢谢

【问题讨论】:

  • 哪些 drawable-x 文件夹包含您的图像?
  • 我暂时把所有东西都放在了 mdpi 文件夹中。

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


【解决方案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;
}

【讨论】:

    【解决方案2】:

    Galaxy S4 很可能与 xxhdpi 可绘制对象一起使用,因此将所有内容放入 mdpi 将使系统放大图像以匹配 S4 的 dpi 级别,因此出现 OutOfMemory 错误。尝试根据 dpi(包括 xhdpixxhdpi)在各自的文件夹中缩放和放置可绘制对象,然后可能会优化您的代码。

    【讨论】:

    • 我试过很快,看来你是对的。图像替换更平滑,堆增长更慢(大小减半)。明天我会努力的更好。现在谢谢。
    猜你喜欢
    • 2016-02-12
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    相关资源
    最近更新 更多