How to have an ImageView with corners rounded and bordered while using setClipToOutline

Viewed 702

following up on this answer, how can i achieve the same but including a border that runs smoothly around the clipped ImageView.

I have tried using this as a background drawable for the ImageView with red borders and imageView.setClipToOutline(true).

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/transparent" />
    <corners
        android:radius="35" />
    <stroke
        android:width="2dp"
        android:color="#E42323" />
    <padding
        android:bottom="2dp"
        android:left="2dp"
        android:right="2dp"
        android:top="2dp" />
</shape>

when not using an image as Android:src it works fine.

but when i use Android:src the borders are clipped as well.

note: I know one can use a FrameLayout with ImageView as a child and set the background drawable to the FrameLayout but that's just asking for issues.

1 Answers

Ok, I don't think this is a solution you expected but as there was no easy solution I could find for the question instead came up with a funny workaround if API level >= 23, but since it works thought I'll share it incase it helps someone.

Basically, set the same drawable used as background and set it as

android:foreground="@drawable/background"

you still need to set background in order for setClipToOutline to clip the drawable properly, and foreground will create an overlapping border on the outside.

Even though foreground makes use of FrameLayout but since its for the same ImageView didn't find any issues with animations, they seem to work fine with it.

Related