项目中有一个需求,就是展示图片宽度铺满,但是高度是要自动缩放的。 来上一个最普通的代码:
<ImageView
android:id="@+id/img_background"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@mipmap/qr1"
android:scaleType="centerCrop"/>
在平板上,大屏幕尺寸的效果是这样
这么丑,怎么可以忍?真实的效果应该要这样的:
好了,下面说下怎么做的。
1、加上android:adjustViewBounds=”true”,它的作用是保持宽高比。
<ImageView
android:id="@+id/img_background"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
android:src="@mipmap/qr1" />
2、代码
ViewTreeObserver vto = img_background.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
img_background.getViewTreeObserver().removeGlobalOnLayoutListener(this);
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels; // 屏幕宽度(像素)
int height = dm.heightPixels; // 屏幕高度(像素)
int screenWidth =width; // 获取屏幕宽度
ViewGroup.LayoutParams lp = img_background.getLayoutParams();
lp.width = screenWidth;
lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
img_background.setLayoutParams(lp);
img_background.setMaxWidth(screenWidth);
img_background.setMaxHeight(screenWidth * 5);
}