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

后端 未结 8 1897
面向向阳花
面向向阳花 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)
        }
    }
    
    0 讨论(0)
  • 2020-12-04 11:26

    There is no viable solution within the XML layout standard.

    The only reliable way to react to a dynamic image size is to use LayoutParams in code.

    Disappointing.

    0 讨论(0)
提交回复
热议问题