Rounded image view in Android

“Interior of San Francisco Museum of Modern Art architecture in circular white room with walkway” by Sebastien Gabriel on Unsplash

The common use-case is like this: you need to get an image from some server, resize and cache it (you’re using Picasso for this, aren’t you?), make corners rounded (ok, this is not the most popular use-case, but it’s what this article is about) and load it into view. So, how can we make rounded corners?

As usual, we have several ways to achieve this in Android.

Option #1. Overlay

Option #2. clipPath

Option #3. BitmapShader

Option #4. RoundedBitmapDrawable

As we will use our view with Picasso only, we don’t even need to inherit it from ImageView, simple View would be enough:

class RoundedImageView(
context: Context,
attributeSet: AttributeSet?
) : View(context, attributeSet), Target {
constructor(context: Context) : this(context, null)

In order to allow Picasso to load an image into our view, it should implement Target interface, which includes 3 methods: onPrepareLoad, onBitmapFailed and onBitmapLoaded. All the magic is done in onBitmapLoaded method:

override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
val roundedDrawable = RoundedBitmapDrawableFactory.create(resources, bitmap)
roundedDrawable.cornerRadius = dip(DEFAULT_RADIUS).toFloat()
drawable = roundedDrawable

Finally, we need to draw our Drawable in onDraw method (sounds very reasonable, isn’t it?):

override fun onDraw(canvas: Canvas?) {
drawable?.setBounds(0, 0, width, height)

So the complete code together with helper method for loading image by URL string is here:

That’s all! If you have any questions or notes, feel free to leave a comment.

Head of Applications @ Mews

Head of Applications @ Mews