Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageView fit width, start from top

I have an image want it to fit width, but since it's long, I need to keep topmost part visible, I tried using ImageView :

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@mipmap/day_length_background"
    android:scaleType="centerCrop"
    android:adjustViewBounds="true"
    />

But result is :

enter image description here

I can't use fitXY, because it changes aspect ratio.

I need it to be like this enter image description here

like image 228
AVEbrahimi Avatar asked Jun 12 '26 14:06

AVEbrahimi


1 Answers

You can use this implementation of TopCropImageView:

class TopCropImageView : AppCompatImageView {
    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        recomputeImgMatrix()
    }

    override fun setFrame(l: Int, t: Int, r: Int, b: Int): Boolean {
        recomputeImgMatrix()
        return super.setFrame(l, t, r, b)
    }

    private fun init() {
        scaleType = ScaleType.MATRIX
    }

    private fun recomputeImgMatrix() {
        val drawable = drawable ?: return
        val matrix = imageMatrix
        val scale: Float
        val viewWidth = width - paddingLeft - paddingRight
        val viewHeight = height - paddingTop - paddingBottom
        val drawableWidth = drawable.intrinsicWidth
        val drawableHeight = drawable.intrinsicHeight
        scale = if (drawableWidth * viewHeight > drawableHeight * viewWidth) {
            viewHeight.toFloat() / drawableHeight.toFloat()
        } else {
            viewWidth.toFloat() / drawableWidth.toFloat()
        }
        matrix.setScale(scale, scale)
        imageMatrix = matrix
    }
}

Top will get aligned and view will get cropped at bottom.

like image 93
Kostek Avatar answered Jun 17 '26 06:06

Kostek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!