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
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)
}
}
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.