[英]Android ImageView not scaling to screen width
我正在使用以下功能将任何图像缩放到屏幕宽度:
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。这意味着位图或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
将imageView的Width设置为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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.