我正在尝试将更大尺寸的位图设置为固定高度和宽度的图像视图,
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);
设置更大尺寸和固定高度和宽度的图像还有哪些选项可以帮助
答案 0 :(得分: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
是您所需的宽度和高度(以像素为单位)。
如果您的位图 lot 小于您想要的尺寸,则无法在不模糊的情况下进行扩展。使用更高质量的位图。