Search code examples
androidxmlkotlin

Is there any way to contour only the image (not the whole ImageView) in Android?


The aspect ratios of the images may differ significantly and scaling isn't acceptable in my case. Is there any way to contour only the images?

None of the articles I've seen solved my problem.


Solution

  • By contour you mean drawing border on image which is inside a ImageView, you can do 2 things.

    Solution 1: Add background, padding and set adjustViewBounds = true.

        <ImageView
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:background="#A30000"
            android:adjustViewBounds="true"
            android:padding="4dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:src="@drawable/test2"
            />
    

    In the above example, I've set the width to 200dp and the height of the ImageView is being adjusted according to th image ration. and it is possible because of adjustViewBounds. for border I'm using padding of 4dp with background="#A30000". Check the Image below.

    enter image description here

    Solution 2: Create a custom ImageView and draw a border with help of onDraw() function. I have created a below custom ImageView. you can use it directly or modify it according to your usecase.

    https://github.com/vishalnaikawadi/miscellaneous/blob/main/ContourImageView

        <com.vmn.theschoolofrock.utils.ContourImageView
            android:layout_width="400dp"
            android:layout_height="400dp"
            android:background="#ffffff"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:src="@drawable/test2"
            />
    
    

    I have used Color.RED for drawing the outline

    enter image description here