所以,我正在缩小位图文件,这样我就可以在不超过内存大小的情况下显示图像。我在这里参考了 android 教程。
我发现,这不仅缩小了我的图像尺寸,因此尺寸不会太大,而且还切断了图像的一部分。或者看起来是这样。我只希望图像占据屏幕的一部分。如何缩小位图并显示整个图像?
如果您能提供任何帮助、想法或建议,我将不胜感激!如果我似乎犯了一个简单的错误,请向我指出。谢谢!
这是代码:
String fileName = data.getStringExtra("file");
image.setImageBitmap(decodeSampledBitmapFromFile(fileName, screenWidth, screenHeight / 2));
public static Bitmap decodeSampledBitmapFromFile(String file, int reqWidth, int reqHeight){
//first decode with inJustDecodeBounds = true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, options);
//calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
//decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
System.gc();
return BitmapFactory.decodeFile(file, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight){
//raw height and width of image
final int imageHeight = options.outHeight;
final int imageWidth = options.outWidth;
int inSampleSize = 1;
if (imageHeight > reqHeight || imageWidth > reqWidth){
if (imageWidth > imageHeight){
inSampleSize = Math.round((float) imageHeight / (float) reqHeight);
}else{
inSampleSize = Math.round((float) imageWidth / (float) reqWidth);
}//end of second if statement
}//end of first if statement
return inSampleSize;
}//end of calculateInSampleSize
public void getDisplaySize(){
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
//get the screen dimensions
try{
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
buttonHeight = view.getHeight();
screenLength = (int) (screenHeight / 5);
imageWidth = (int) (screenWidth / 4);
}catch (NoSuchMethodError e){
//for older versions of android
screenWidth = display.getWidth();
screenHeight = display.getHeight();
buttonHeight = view.getHeight();
screenLength = (int) (screenHeight / 5);
imageWidth = (int) (screenWidth / 4);
}//end of try/catch block
}//end of getDisplaySize() method