android - 修复了大尺寸位图问题的高度和宽度 ImageView

标签 android android-imageview android-image

我正在尝试将较大尺寸的位图设置为固定高度和宽度的 ImageView ,

xml 中的 ImageView

 <ImageView
       android:id="@+id/imgDisplay"
       android:layout_width="320dp"
       android:layout_height="180dp"
       android:layout_marginLeft="10dp"
       android:layout_marginTop="5dp"
       android:contentDescription="@string/app_name" />

当我使用以下代码时,可以避免错误,但由于 BitmapFactory.Options 选项,出现的图像变得模糊,

BitmapFactory.Options options = new BitmapFactory.Options(); 
            options.inPurgeable = true;
            options.inSampleSize = 4;
            Bitmap myBitmap = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/"+photo, options);
            imgMainItem.setImageBitmap(myBitmap);

还有什么选项可以设置更大尺寸和固定高度和宽度的图像,请帮忙

最佳答案

不要使用固定的样本量。首先计算您需要的样本量,如下所示:

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

然后,像这样使用它:

String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/"+photo;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, width, height);

options.inJustDecodeBounds = false;
Bitmap myBitmap = BitmapFactory.decodeFile(path, options);
imgMainItem.setImageBitmap(myBitmap);

widthheight 是您所需的宽度和高度(以像素为单位)。

如果您的位图比您想要的尺寸小很多,则无法在不模糊的情况下真正放大它。使用更高质量的位图。

关于android - 修复了大尺寸位图问题的高度和宽度 ImageView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16938052/

相关文章:

android - 如何从我的 android 设备而不是 sdcard 获取所有图像和照片?

java - 如何使用 ValueAnimator#ofFloat

android - 如何在不使用任何按钮的情况下发送短信

android - 如何获取使用 Volley ImageLoader 下载的缓存位图?

android - 前景在真实设备中不可见但在模拟器中可见

Android 文件提供程序非法参数异常

android - 支持和反对 Android SQLite 使用的论点

android - ELF Android 系统库中 .rel.dyn 部分的用途

android-imageview - 如何从 Firebase 存储检索图像并显示它?获取 "No content provider"错误

android - CenterCrop 缩放类型不适用于使用 Picasso 加载的图像