Android - ImageView 是否会调整图像的大小(并且不保存原始图像)?

Android - Does an ImageView resizes the image (and doesn't save the original)?

很简单的问题,找不到答案..

我想知道即使 ImageView 显示原始图像的较小版本 - 它是否仍然使用原始图像的全部内存大小..? (我指的是从 SD 卡而非资源加载的图像)

是的,它将使用原始尺寸。在分配给 ImageView 之前,您必须调整所有位图的大小,否则您将遇到很多 Out Of Memory Error 问题。

您还应该计算 ImageView 的最终大小并调整 Bitmap 的大小。

一些代码可以让你继续。

private static Bitmap createBitmap(@NonNull String filePath, int width )
{
    BitmapFactory.Options options = new BitmapFactory.Options();

    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath , options );

    // Getting original image properties
    int imageHeight = options.outHeight;
    int imageWidth = options.outWidth;


    int scale       = -1;
    if ( imageWidth < imageHeight ) {
        scale   = Math.round( imageHeight / width );
    } else {
        scale   = Math.round(imageWidth / width);
    }
    if ( scale <= 0 )
        scale = 1;

    options.inSampleSize    = scale;
    options.inJustDecodeBounds  = false;

    // Create a resized bitmap
    Bitmap scaledBitmap = BitmapFactory.decodeFile(filePath , options);
    return scaledBitmap;
}

您还应该考虑:

  • 维护主线程外的所有位图操作。
  • 正确处理并发
  • 利用一些开源库,例如 one