2

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

xml中的图像视图

 <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);

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

4

1 回答 1

2

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

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);

width并且height是您所需的宽度和高度(以像素为单位)。

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

于 2013-06-05T11:03:31.037 回答