Android. ImageView keep the aspect ratio of full screen image

585 Views Asked by At

I have a full screen image. I receive the imagefrom the server and it can be of any size. I need to display this image in full screen.

However, on some devices, part of the image is cropped.This was due to the fact that I had set scaleType of my ImageView centerCrop. Accordingly, in order for the whole imageto be displayed on the screen, and not to be cropped, I changed the scaleType to fitXY. Now, no part of the image is cropped, but fitXY does not keep the aspect ratio of the image, and as a result, some of the details in the image are stretched.

Is it possible to keep the aspect ratio of the picture without cropping it? Please help me.

I also tried to create custom ImageView to keep aspect ratio, and set scaleType to fixXY, but it is not working, the image still looks stretched. Here is my code:

class ScaleImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : AppCompatImageView(context, attrs, defStyle) {

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) = try {
        val drawable = drawable
        if (drawable == null) {
            setMeasuredDimension(0, 0)
        } else {
            val measuredWidth = MeasureSpec.getSize(widthMeasureSpec)
            val measuredHeight = MeasureSpec.getSize(heightMeasureSpec)
            if (measuredHeight == 0 && measuredWidth == 0) {
                setMeasuredDimension(measuredWidth, measuredHeight)
            } else if (measuredHeight == 0) { 
                val height = measuredWidth * drawable.intrinsicHeight / drawable.intrinsicWidth
                setMeasuredDimension(measuredWidth, height)
            } else if (measuredWidth == 0) { 
                val width = measuredHeight * drawable.intrinsicWidth / drawable.intrinsicHeight
                setMeasuredDimension(width, measuredHeight)
            } else { 
                setMeasuredDimension(measuredWidth, measuredHeight)
            }
        }
    } catch (e: Exception) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }
}

I also tried this way:

<ImageView
    android:scaleType="centerCrop"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true" />

But in this case, the picture is cropped at the top and bottom(

0

There are 0 best solutions below