我正在使用以下功能将任何图像缩放到屏幕宽度:
DisplayMetrics metrics = new DisplayMetrics();
((Activity)context)
.getWindowManager()
.getDefaultDisplay()
.getMetrics(metrics);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
// Calculate the ratio between height and width of Original Image
float ratio = (float) height / (float) width;
int newWidth = metrics.widthPixels; // This will be equal to screen width
float newHeight = newWidth * ratio; // This will be according to the ratio calulated
// calculate the scale
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = newHeight / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap
= Bitmap.createBitmap(
bitmap, 0, 0,
width, height,
matrix, true
);
// make a Drawable from Bitmap to allow to set the BitMap
// to the ImageView, ImageButton or what ever
return new BitmapDrawable(resizedBitmap);
进行一些检查后,值为 metrics.widthPixels = 540 ,新位图的宽度也为540.这意味着Bitmap或Imageview应使用全屏宽度。相反,生成的图像视图缺少全屏宽度。我包括一个截图:
如图所示,屏幕的剩余空白部分以黑色显示。
创建ImageView的代码是:
ImageView imageBanner = new ImageView(context);
imageBanner.setLayoutParams(new
LinearLayout.LayoutParams(
Globals.wrapContent,
Globals.wrapContent));
imageBanner.setBackgroundResource(R.drawable.imv_banner);
new SyncImage(context, imageBanner, urlImage).execute();
Globals.wrapContent是显式常量,它包含标准布局参数的相同值,因此不要将它们视为不同。 SyncImage用于在ImageView中下载和显示图像的异步类。
请提供解决方案,将图像缩放到全屏宽度,图像应保持原始尺寸比。
谢谢 Ram Ram
答案 0 :(得分:0)
将imageView的宽度设置为MatchParent而不是WrapContent,并计算高度以保持图像的宽高比。请尝试以下代码来调整图像大小:
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int newWidth = size.x;
//Get actual width and height of image
int width = bitmap.getWidth();
int height = bitmap.getHeight();
// Calculate the ratio between height and width of Original Image
float ratio = (float) height / (float) width;
float scale = getApplicationContext().getResources().getDisplayMetrics().density;
int newHeight = (int) (width * ratio)/scale;
return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);