[英]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.