Circle Image In Xamarin.Forms Using CustomRenderer

Introduction

Circular images in apps are very popular in app development nowadays. For most of the applications, we need to make user profile a  circlular image. So in this article, we will learn how to make an image circle using CustomRenderer.

Requirements

  • This article source code is prepared by using Visual Studio. And it is better to install the latest Visual Studio updates from here.
  • This article is prepared on a MAC machine.
  • This sample project is Xamarin.Forms PCL project.
  • This sample app is targeted for Android, iOS. And tested for Android & iOS.

Description

The creation of a Xamarin.Forms project is very simple in Visual Studio for Mac. It will create three projects:

  1. Shared Code
  2. Xamarin.Android
  3. Xamarin.iOS

The Mac system with Visual Studio for Mac doesn't support Windows projects (UWP, Windows, Windows Phone).

The following steps will show you how to create Xamarin.Forms projects in a Mac system with Visual Studio.

First, open Visual Studio for Mac. And click on New Project.

After that, we need to select whether you're doing Xamarin.Forms or Xamarin.Android or Xamarin.iOS project. If we want to create Xamarin.Forms project just follow the below screenshot.

Xamarin

Then, we have to give the app name; i.e., ImageCircleDemo.

Xamarin

Note

In the above screen under Shared Code, select Portable class Library or Use Shared Library.

Then, click on Next Button and the following screenshot will be displayed. In that screen, we have to browse the file path where we want to save that application on our PC.

Xamarin

After clicking on the create button it will create the ImageCircleDemo Xamarin.Forms project like below.

Xamarin

And the project structure will be,

  • ImageCircleDemo: It is for Shared Code
  • ImageCircleDemo.Droid: It is for Android.
  • ImageCircleDemo.iOS: It is for iOS
Xamarin
We need to follow the below steps to make ImageCircle.

Portable Class Library (PCL)

Step 1

In PCL, create a class name ImageCircle which should inherit any Image like below.

ImageCircleDemo.cs

  1. using Xamarin.Forms;  
  2. namespace ImageCircleDemo.CustomControls {  
  3.     public class ImageCircle: Image {}  

Step 2

Create your own Xaml page named ImageCirclePage.xaml, and make sure to refer to  "ImageCircle" class in Xaml by declaring a namespace for its location and using the namespace prefix on the control element. The following code example shows how the "ImageCircle" renderer class can be consumed by a Xaml page:

ImageCirclePage.xaml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
  3. BackgroundColor="White" 
  4. xmlns:custom="clr-namespace:ImageCircleDemo.CustomControls;assembly=ImageCircleDemo" 
  5. xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
  6. x:Class="ImageCircleDemo.Views.ImageCirclePage">  
  7.     <Grid Padding="10,20,10,10" RowSpacing="10">  
  8.         <Grid.RowDefinitions>  
  9.             <RowDefinition Height="Auto" />  
  10.             <RowDefinition Height="*" />  
  11.             <RowDefinition Height="Auto" />  
  12.             <RowDefinition Height="Auto" /> </Grid.RowDefinitions>  
  13.         <Label Text="Normal Image" Row="0" FontSize="20" HorizontalOptions="CenterAndExpand" />  
  14.         <Image Aspect="AspectFill" Source="BG.png" Row="1" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />  
  15.         <Label Text="Circle Image" Row="2" FontSize="20" HorizontalOptions="CenterAndExpand" />  
  16.         <custom:ImageCircle Source="BG.png" Row="3" WidthRequest="100" HeightRequest="100" Aspect="AspectFill" VerticalOptions="Start" HorizontalOptions="CenterAndExpand" /> </Grid>  
  17. </ContentPage>  

Note

The "custom" namespace prefix can be named anything. However, the clr-namespace and assembly values must match the details of the custom renderer class. Once the namespace is declared the prefix is used to reference the custom control.

ImageCirclePage.xaml.cs

  1. using Xamarin.Forms;  
  2. namespace ImageCircleDemo.Views {  
  3.     public partial class ImageCirclePage: ContentPage {  
  4.         public ImageCirclePage() {  
  5.             InitializeComponent();  
  6.         }  
  7.     }  
  8. }  

Xamarin.Andriod

ImageCircleRenderer.cs

  1. using System;  
  2. using Android.Graphics;  
  3. using Android.Views;  
  4. using ImageCircleDemo.CustomControls;  
  5. using ImageCircleDemo.Droid.CustomControls;  
  6. using Xamarin.Forms;  
  7. using Xamarin.Forms.Platform.Android;  
  8. [assembly: ExportRenderer(typeof(ImageCircle), typeof(ImageCircleRenderer))]  
  9. namespaceDroid.CustomControls {  
  10.     public class ImageCircleRenderer: ImageRenderer {  
  11.         protected override void OnElementChanged(ElementChangedEventArgs<Image> e) {  
  12.             base.OnElementChanged(e);  
  13.             if (e.OldElement == null) {  
  14.                 if ((int) Android.OS.Build.VERSION.SdkInt < 18) 
  15.                       SetLayerType(LayerType.Software, null);  
  16.             }  
  17.         }  
  18.         protected override bool DrawChild(Canvas canvas, global::Android.Views.View child, long drawingTime) {  
  19.             try {  
  20.                 var radius = Math.Min(Width, Height) / 2;  
  21.                 var strokeWidth = 10;  
  22.                 radius -= strokeWidth / 2;  
  23.                 Path path = new Path();  
  24.                 path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);  
  25.                 canvas.Save();  
  26.                 canvas.ClipPath(path);  
  27.                 var result = base.DrawChild(canvas, child, drawingTime);  
  28.                 canvas.Restore();  
  29.                 path = new Path();  
  30.                 path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);  
  31.                 var paint = new Paint();  
  32.                 paint.AntiAlias = true;  
  33.                 paint.StrokeWidth = 5;  
  34.                 paint.SetStyle(Paint.Style.Stroke);  
  35.                 paint.Color = global::Android.Graphics.Color.White;  
  36.                 canvas.DrawPath(path, paint);  
  37.                 paint.Dispose();  
  38.                 path.Dispose();  
  39.                 return result;  
  40.             } catch (Exception ex) {  
  41.                 var msg = ex.Message;  
  42.             }  
  43.             return base.DrawChild(canvas, child, drawingTime);  
  44.         }  
  45.     }  
  46. }  

The call to the base class's OnElementChanged method instantiates an Android ImageView, with a reference to the control being assigned to the renderer's property. The Canvas class holds the "draw" calls. To draw something, you need 4 basic components: a Bitmap to hold the pixels, a Canvas to host the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, Path, text, Bitmap), and paint (to describe the colors and styles for the drawing).

Output: 

Xamarin

Xamarin.iOS

In iOS project, create a class name:

ImageCircleRenderer.cs

  1. using System;  
  2. using System.ComponentModel;  
  3. using System.Diagnostics;  
  4. using ImageCircle.CustomControls;  
  5. using ImageCircle.iOS.CustomControls;  
  6. using Xamarin.Forms;  
  7. using Xamarin.Forms.Platform.iOS;  
  8. [assembly: ExportRenderer(typeof(ImageCircle), typeof(ImageCircleRenderer))]  
  9. namespace ImageCircle.iOS.CustomControls {  
  10.     public class ImageCircleRenderer: ImageRenderer {  
  11.         protected override void OnElementChanged(ElementChangedEventArgs<Image> e) {  
  12.             base.OnElementChanged(e);  
  13.             if (e.OldElement != null || Element == nullreturn;  
  14.             CreateCircle();  
  15.         }  
  16.         protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) {  
  17.             base.OnElementPropertyChanged(sender, e);  
  18.             if (e.PropertyName == VisualElement.HeightProperty.PropertyName || PropertyName == VisualElement.WidthProperty.PropertyName) {  
  19.                 CreateCircle();  
  20.             }  
  21.         }  
  22.         private void CreateCircle() {  
  23.             try {  
  24.                 double min = Math.Min(Element.Width, Element.Height);  
  25.                 Controls.Layer.CornerRadius = (float)(min / 2.0);  
  26.                 Controls.Layer.MasksToBounds = false;  
  27.                 Controls.Layer.BorderColor = Color.White.ToCGColor();  
  28.                 Controls.Layer.BorderWidth = 1;  
  29.                 Controls.ClipsToBounds = true;  
  30.             } catch (Exception ex) {  
  31.                 WriteLine("Unable to create circle image: " + ex);  
  32.             }  
  33.         }  
  34.     }  
  35. }  

The call to the base class's method OnElementChanged instantiates an iOS control UIImage, with a reference to the control being assigned to the renderer's property Control.

Output: 

Xamarin        

 
Please download the sample from here


Similar Articles