Circular images in your Android app using Volley.

Your app still doesn’t have any image masked with a circle shape and with a nice border around? Let’s add a class to your app and get rid of old rectangular boring images. I can’t say circle is much better than rectangle, but maybe. Anyway, it’s a trend for 2–3 years already!

Nice!
Circles, yeah!

We will use V0lley framework. Why Volley? Because it’s featured by Google and it’s a really cool framework. So why not? Add Volley to your project dependencies like this and sync gradle.

Volley has a great ready to use class NetworkImageView. There are tons of cool things out of the box like custom loaders, caches etc. We will nest from this class to make it shape our image automatically.

Our class is a child of NetworkImageView

What methods should we override now? NetworkImageView contains 3 constructors and a small method setImageBitmap. There are much more great things inside but we will skip them. Look at setImageBitmap. We create a new BitmapDrawable and pass getCircularBitmap(bitmap) method as a second parameter. BitmapDrawable constructor signature is BitmapDrawable(Resources res, Bitmap bitmap). This method is exactly what we use to assign our future result.

Override

This is our method and it’s really straightforward. Let’s go step-by-step through.

Magic

First of all we define new future image by defining a canvas with the size equal to original image. It has 4 channels RGB and A. That’s 8 bit image. Also let’s define stroke width. Surely you should define it outside of the class but we will do this inside the method for the sake of clarity. Also we should find smallest side of an image bounding box, that will be our diameter.

Color constant is 8 bits integer which is a mask color. It should be white to work well with blending mode which is SRC_IN:

SRC_IN [Sa * Da, Sa * Dc]

Next we set anti alias flag to true to avoid aliased edge. Fill background with black color. Set white color and draw a circle on canvas. Then draw a bitmap on top of the circle and set blending mode.

Next add a stroke using predefined stroke width and set your favorite color. It should be set outside of the class but we set it here for the sake of clarity too. The last 3 rows define and draw a nice circle around the image.

That’s it! You can find full source code here: pharosproduction/CircularNetworkImageView.java


DONE

You’re welcome to hire us at Pharos Production Inc.

Thanks for reading!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.