android之路

Android 设置 ImageView 高度固定,宽度自适应

2018-02-04  本文已影响118人  innovatorCL

1. 需求背景

当很多时候,设计为了界面美观,都会设死图片的宽度或者高度,但是服务器返回的图片参差不齐,这时候就需要我们手动设置 ImageView 宽高了,通过 ImageView 的 android:adjustViewBounds="true" 属性,我们能让设置让图片自适应显示。

2. 实现方式

<ImageView android:id="@+id/test_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:src="#EEEEEE" />

注意:android:adjustViewBounds="true" 属性只有在设置了最大高度和最大宽度后才会起作用,所以我们要在代码里面设置最大的宽高。

show my code

if(0 == screenWidth){
    // 获取屏幕的宽度,以 dp 为单位返回
    screenWidth = CommonUtils.getScreenWidthDp(mContext);
  }

// 此处设置高度是固定的,是 (屏幕 - 40dp) * 0.75
int fixedHeight = CommonUtils.dip2px(mContext,(float) ((screenWidth - 40) * 0.75));
ViewGroup.LayoutParams lp = holder.contentImage.getLayoutParams();
lp.width = ViewGroup.LayoutParams.WRAP_CONTENT;
lp.height = fixedHeight;
contentImage.setLayoutParams(lp);

contentImage.setMaxWidth(CommonUtils.dip2px(mContext, screenWidth - 40));
contentImage.setMaxHeight(fixedHeight);

接下来就可以用 Glide 来加载显示图片啦!!!

Glide.with(mContext).load(url).crossFade().priority(Priority.IMMEDIATE)//.thumbnail(0.1f)
            .diskCacheStrategy(DiskCacheStrategy.SOURCE)
            .placeholder(new ColorDrawable(mContext.getResources().getColor(R.color.clicked)))
            .into(contentImage);

效果图

效果.jpg
上一篇 下一篇

猜你喜欢

热点阅读