Android之ImageView宽高适配

Android ImageView图片宽度为控件宽度,高度按比例缩放

实现方式

在Java代码里面实现

首先,定义ImageView,在该ImageView中,我们需要设置属性android:adjustViewBounds=”true”,他的意思图片是否保持宽高比。切记的一点是该属性需要与maxWidth、MaxHeight一起使用,否则单独使用没有效果。

1
2
3
4
5
6
7
<ImageView
android:id="@+id/img_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
android:src="@drawable/load_default_img" />

刚刚说了,android:adjustViewBounds=”true”必须与MaxHeight一起使用才能有效,所以,我要设置该ImageView的最大高度MaxHeight:

1
2
3
4
5
6
7
8
int screenWidth = getScreenWidth(this); // 获取屏幕宽度a
ViewGroup.LayoutParams lp = testImage.getLayoutParams();
lp.width = screenWidth;
lp.height = LayoutParams.WRAP_CONTENT;
testImage.setLayoutParams(lp);

testImage.setMaxWidth(screenWidth);
testImage.setMaxHeight(screenWidth * 5); //这里其实可以根据需求而定,我这里测试为最大宽度的5倍

在Xml中实现

1
2
3
4
5
6
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
android:src="@drawable/ic_login_bg" />

参考:

1、Android 设置ImageView宽度固定,其高度按比例缩放适应