Circular Images in Android App Using Volley.

Mobile Apps Development A-Z Guide.

Dmytro Nasyrov
Pharos Production
3 min readMay 14, 2017

--

Give us a message if you’re interested in Blockchain and FinTech software development or just say Hi at Pharos Production Inc.

Or follow us on Youtube to know more about Software Architecture, Distributed Systems, Blockchain, High-load Systems, Microservices, and Enterprise Design Patterns.

Pharos Production Youtube channel

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 the circle is much better than a 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 a new future image by defining a canvas with the size equal to the 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 the smallest size of an image bounding box, that will be our diameter.

A 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 the aliased edge. Fill the 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 the full source code here: pharosproduction/CircularNetworkImageView.java

Thanks for reading!

--

--

Dmytro Nasyrov
Pharos Production

We build high-load software. Pharos Production founder and CTO.