我正在尝试将较大尺寸的位图设置为固定高度和宽度的 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);
width
和 height
是您所需的宽度和高度(以像素为单位)。
如果您的位图比您想要的尺寸小很多,则无法在不模糊的情况下真正放大它。使用更高质量的位图。
关于android - 修复了大尺寸位图问题的高度和宽度 ImageView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16938052/