Elegant Circle Images in Xamarin.Forms



Circular images in apps are currently a popular trend in mobile, and it is a simple technique that can add a lot of polish to your mobile apps. We made use of them in this year’s Xamarin Evolve mobile apps, and with a little bit of code and a single custom renderer, you too can transform standard images in Xamarin.Forms into these elegant round images.


Custom Image

After you create your Xamarin.Forms project, the first thing you need to do is create a custom control that inherits from Image. Let’s call this ImageCircle and then implement the custom renderers on each platform.

Custom Renderers

Now you just need to tell Xamarin.Forms how to render this new ImageCircle on each platform by using custom renderers.

For all three projects, you will need to create an ImageCircleRenderer that inherits from ImageRenderer and then implement how to cut out the circle image.

iOS Renderer

For iOS you are able to directly interact with the CALayer of our UIImageView to add a corner radius and set the border color.

This method should be called on the initial OnElementChanged or when the Height or Width properties are updated:

And of course you must export the renderer with an assembly export:

Android Renderer

Android is a unique platform; you don’t have a physical layer to interact with, however, you are able to modify how Xamarin.Forms draws the child and cut out a path from the canvas. This method is a bit of complex math, but calculates the path to clip and then adds a circular border around the child.

One intricate part here is that Android handles the clipping of paths differently depending on the version of Android. Hardware acceleration for this method was introduced in API 18, so you must tell Android to use software rendering on older devices. You can set the layer type flag in the OnElementChanged method:

And of course you must export the renderer with an assembly export:

Windows Phone Renderer

Last, but not least, we come to Windows Phone, which has a Clip property that you can use to create EllipseGeometry to cut out the circle from the image:

And of course you must export the renderer with an assembly export:

Custom Cell

With all of the custom renders in place, you can simply use your new ImageCircle anywhere you would like, including custom ViewCells for your ListViews. The key here is to ensure that you request the same Width & Height for your image and set the Aspect to AspectFill to ensure a perfect square to cut your circle from.


See the Code in Action

You can grab the entire source code from GitHub. Additionally, I sat down with Xamarin’s own Steven Yi at this year’s Xamarin Evolve to explain how I implemented and used Circle Images in the Xamarin Evolve mobile apps:

James Montemagno

Principal Program Manager, Mobile Developers Tools

Follow James   

No Comments.