Android ImageView scale smaller image to width with flexible height without cropping or distortion

后端 未结 8 1928
面向向阳花
面向向阳花 2020-12-04 10:55

Often asked, never answered (at least not in a reproducible way).

I have an image view with an image that is smaller than the view. I want to scale

8条回答
  •  执念已碎
    2020-12-04 11:24

    Kotlin version of Mark Martinsson's answer:

    class DynamicImageView(context: Context, attrs: AttributeSet) : AppCompatImageView(context, attrs) {
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val drawable = this.drawable
    
        if (drawable != null) {
            //Ceil not round - avoid thin vertical gaps along the left/right edges
            val width = View.MeasureSpec.getSize(widthMeasureSpec)
            val height = Math.ceil((width * drawable.intrinsicHeight.toFloat() / drawable.intrinsicWidth).toDouble()).toInt()
            this.setMeasuredDimension(width, height)
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        }
    }
    

提交回复
热议问题