How to make an ImageView with rounded corners?

前端 未结 30 3300
天涯浪人
天涯浪人 2020-11-21 05:39

In Android, an ImageView is a rectangle by default. How can I make it a rounded rectangle (clip off all 4 corners of my Bitmap to be rounded rectangles) in the ImageView?

30条回答
  •  佛祖请我去吃肉
    2020-11-21 06:23

    Clipping to rounded shapes was added to the View class in API 21.

    Just do this:

    • Create a rounded shape drawable, something like this:

    res/drawable/round_outline.xml

    
        
        ...
    
    
    • Set the drawable as your ImageView's background: android:background="@drawable/round_outline"
    • According to this documentation, then all you need to do is add android:clipToOutline="true"

    Unfortunately, there's a bug and that XML attribute is not recognized. Luckily, we can still set up clipping in Java:

    • In your activity or fragment: ImageView.setClipToOutline(true)

    Here's what it will look like:

    enter image description here

    Note:

    This method works for any drawable shape (not just rounded). It will clip the ImageView to whatever shape outline you've defined in your Drawable xml.

    Special note about ImageViews

    setClipToOutline() only works when the View's background is set to a shape drawable. If this background shape exists, View treats the shape's outline as the borders for clipping and shadowing purposes.

    This means, if you want to use setClipToOutline() to round the corners on an ImageView, your image must be set using android:src instead of android:background (since background must be set to your rounded shape). If you MUST use background to set your image instead of src, you can use this workaround:

    • Create a layout and set its background to your shape drawable
    • Wrap that layout around your ImageView (with no padding)
    • The ImageView (including anything else in the layout) will now display with rounded layout shape.

提交回复
热议问题