androidxmlandroid-layoutimageviewscale

How to scale an image to the top center? - Android


I have an imageview as background. It is bigger than screen. I want to center it horizontally. It should align to the top. So, top of the original image should seen in the screen. I can resize the original images if necessary.

For example, in the giraffe image, I should be able to see from head to neck, not to the foot. Because the width allows that much.

XML Code

...

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     >

    <ImageView
        android:id="@+id/imageView5"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="matrix"
        android:src="@drawable/home_screen_wallpaper_image"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Image to what i want when image is too big to phone size, scale should be like this


Solution

  • The usual scale types will not work for you. You will need to use the MATRIX scale type.

    Here is how to apply it:

    binding.matrixImage.doOnNextLayout {
        // We will use a Matrix to shift the image left.
        binding.matrixImage.scaleType = ImageView.ScaleType.MATRIX
        
        // Compute how far to shift the image
        val dx = (binding.matrixImage.drawable.intrinsicWidth - binding.matrixImage.width) / 2f
        
        // Create and set the Matrix.
        val matrix = Matrix()
        matrix.postTranslate(-dx, 0f)
        binding.matrixImage.imageMatrix = matrix
    }