直接上代码:
//获取屏幕宽度
int bannerWidth = ScreenUtil.getScreenWidth(rootView.getContext());
//获取图片宽高
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.design0);
int imgWidth = bitmap.getWidth();
int imgHeight = bitmap.getHeight();
//得到最终显示高度
int finalHeight = bannerWidth * imgHeight / imgWidth;
//设置图片显示高度
imgView.setHeight(finalHeight);
<ImageView
android:id="@+id/img_view"
android:src="@drawable/test"
android:scaleType="fitXY"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
注意:
最后设置的高度为控件的高度,如果是ImageView标签就是ImageView的高度,如果对应的标签没有直接设置高度的属性,可在标签外部嵌套一层LinearLayout并设置它的高度即可(imageView的height要改为match_parent):
layoutBanner.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, finalHeight));