Android ImageView根据宽高比显示图片

1,750 阅读1分钟

在实际项目开发需求中,总是会有固定宽高比的图片显示规则,但是宽度不是固定值,与屏幕宽度或者受父View大小影响,我的通常做法(仅供参考):

方法一:

在Java代码中获取ImageView的LayoutParams,获取到width和height,根据需求,再进行比例设置,计算出具体的宽高值。

注意:在获取LayoutParams,如果直接使用LayoutParams取出宽高值为0,我通常会执行view的post方法,在post方法中去获取LayoutParams,然后再进行计算。

方法二:

可以继承ImageView,根据需求在onMeasure中计算需要的宽高比。

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    var measureWidth: Int = measuredWidth
    var measureHeight: Int = measuredHeight
    if (this.mDomaint == 0
        || this.mRatioWidth == 0 || this.mRatioHeight == 0
        || measureWidth == 0 || measureHeight == 0
    ) {
        return
    }
    if (this.mDomaint == Domaint.HEIGHT.value) {
        measureWidth = measuredHeight * mRatioWidth / mRatioHeight
    } else {
        measureHeight = measuredWidth * mRatioHeight / mRatioWidth;
    }
    val widthSpec: Int = MeasureSpec.makeMeasureSpec(measureWidth, EXACTLY)
    val heightSpec: Int = MeasureSpec.makeMeasureSpec(measureHeight, EXACTLY)
    setMeasuredDimension(widthSpec, heightSpec)
}

为了需求变化,自己撸了这个RatioImageView

Picasso/Glide/Fresco 等图片框架 根据需求修改即可。