Android ImageViews by default don’t have an option to set a corner radius. William J. Francis shares a quick hack that does the trick in a layout file without writing any actual code.
One of the common questions I see on Android forums is: How does one round the corners on the standard Android ImageView widget? The short answer is you don’t. I don’t know why, but the standard out-of-the-box ImageView component doesn’t have a corner radius property. That doesn’t mean it can’t be done.
There are lots of posts on how to extend the ImageView.class, add your own attributes, modify the original bitmap, and override the on draw and paint the image to the canvas. But let’s face it, that is quite a bit of work for something that should have happened “automagically.”
I ran across a clever hack that allows for rounding the corners on an ImageView directly from the XML; it makes use of a FrameLayout and an XML drawable. The short tutorial below explains. Follow along, or download and import the project directly into Eclipse.
1. Create a new Android project in Eclipse targeting SDK 14 (ICS) or better.
2. In the /res/drawable folder, create a frame.xml file. In it, we define a simple rectangle with rounded corners and a transparent center.
3. In the /res/drawable-xhdpi folder include the image you wish to use as the source for your ImageView. In my case, I cut and pasted the TechRepublic logo.
4. In the /res/layout folder modify activity_main.xml. In it, you will see a LinearLayout that contains a standard ImageView, as well as a nested FrameLayout. The FrameLayout uses padding and the custom drawable to give the illusion of rounded corners.
That’s it. No modification is needed to the generated Java code. Have a look for yourself.