[Andorid]Adapter中按比例显示不同高度的图片
@Author GQ 2017年11月09日
最近用到再列表中显示不定高度的图片,需要在列表的每个item中
根据屏幕宽度,按比例显示图片高度
效果图
在列表中按比例显示图片高度
adjustViewBounds
属性和maxWidth
maxHeight
搭配才能起作用!
item中的XML
<ImageView
android:id="@+id/iv_pic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true" // 设置保持宽高比
android:scaleType="centerCrop"/>
Adapter
//获取屏幕宽度
int width;
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// width = wm.getDefaultDisplay().getWidth(); 方法过时
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
width = dm.widthPixels;
//设置图片 maxHeight ,注意RelativeLayout.LayoutParams根据自己的外层写
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.miv_pic.getLayoutParams();
params.width = width;
params.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
holder.miv_pic.setLayoutParams(params);
holder.miv_pic.setMaxWidth(width);
holder.miv_pic.setMaxHeight(width * 5);//设置最高5倍高度,一般足够了,除非要显示长图,自己可调整
//我用的universalimageloader加载图片,可以根据自己的项目换
com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(url, holder.miv_pic);
单张图片按比例显示
一般直接显示单张图片设置
scaleType
即可, 特殊情况也可以用BitmapFactory.Option中的options.inJustDecodeBounds = true
只加载图片边缘得到原图宽高 ,再做其他比例缩放等操作