Scale image on width and crop on height with Coil

145 Views Asked by At

I've a ImageView with fixed height (400dp) and variable width (match parent). I'm using Coil to load the content from the web.

I've some images that are landescape and other that are portrait.

I want to always fit the width and crop the height:

enter image description here

I can't get that.

If I use CenterCrop, the image is cropped on the width if is too large enter image description here

If I use CenterFit, the image doesn't fit the width if it's too tall enter image description here

What's the best way to obtain the desired behaviour?

I tried using all the possible ScaleType, both on the ImageView and the Coil loader.

1

There are 1 best solutions below

0
Squti On

Make a custom ImageView like so:

class CustomImageView(context: Context, attrs: AttributeSet) : AppCompatImageView(context, attrs) {
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        val width = measuredWidth
        val height = measuredHeight

        if (width > height) {
            setMeasuredDimension(width, width)
        } else {
            setMeasuredDimension(height, height)
        }
    }
}

Use it in your layout like this:

<com.example.CustomImageView
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:scaleType="centerCrop" />

And load the image using Coil to this CustomImageView.

Replace com.example with your package name.