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:
- Shared Code
- Xamarin.Android
- 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.
Then, we have to give the app name; i.e., ImageCircleDemo.
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.
After clicking on the create button it will create the ImageCircleDemo Xamarin.Forms project like below.
And the project structure will be,
- ImageCircleDemo: It is for Shared Code
- ImageCircleDemo.Droid: It is for Android.
- ImageCircleDemo.iOS: It is for iOS
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
- using Xamarin.Forms;
- namespace ImageCircleDemo.CustomControls {
- 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
- <?xml version="1.0" encoding="utf-8"?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- BackgroundColor="White"
- xmlns:custom="clr-namespace:ImageCircleDemo.CustomControls;assembly=ImageCircleDemo"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- x:Class="ImageCircleDemo.Views.ImageCirclePage">
- <Grid Padding="10,20,10,10" RowSpacing="10">
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto" />
- <RowDefinition Height="*" />
- <RowDefinition Height="Auto" />
- <RowDefinition Height="Auto" /> </Grid.RowDefinitions>
- <Label Text="Normal Image" Row="0" FontSize="20" HorizontalOptions="CenterAndExpand" />
- <Image Aspect="AspectFill" Source="BG.png" Row="1" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />
- <Label Text="Circle Image" Row="2" FontSize="20" HorizontalOptions="CenterAndExpand" />
- <custom:ImageCircle Source="BG.png" Row="3" WidthRequest="100" HeightRequest="100" Aspect="AspectFill" VerticalOptions="Start" HorizontalOptions="CenterAndExpand" /> </Grid>
- </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
- using Xamarin.Forms;
- namespace ImageCircleDemo.Views {
- public partial class ImageCirclePage: ContentPage {
- public ImageCirclePage() {
- InitializeComponent();
- }
- }
- }
Xamarin.Andriod
ImageCircleRenderer.cs
- using System;
- using Android.Graphics;
- using Android.Views;
- using ImageCircleDemo.CustomControls;
- using ImageCircleDemo.Droid.CustomControls;
- using Xamarin.Forms;
- using Xamarin.Forms.Platform.Android;
- [assembly: ExportRenderer(typeof(ImageCircle), typeof(ImageCircleRenderer))]
- namespaceDroid.CustomControls {
- public class ImageCircleRenderer: ImageRenderer {
- protected override void OnElementChanged(ElementChangedEventArgs<Image> e) {
- base.OnElementChanged(e);
- if (e.OldElement == null) {
- if ((int) Android.OS.Build.VERSION.SdkInt < 18)
- SetLayerType(LayerType.Software, null);
- }
- }
- protected override bool DrawChild(Canvas canvas, global::Android.Views.View child, long drawingTime) {
- try {
- var radius = Math.Min(Width, Height) / 2;
- var strokeWidth = 10;
- radius -= strokeWidth / 2;
- Path path = new Path();
- path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);
- canvas.Save();
- canvas.ClipPath(path);
- var result = base.DrawChild(canvas, child, drawingTime);
- canvas.Restore();
- path = new Path();
- path.AddCircle(Width / 2, Height / 2, radius, Path.Direction.Ccw);
- var paint = new Paint();
- paint.AntiAlias = true;
- paint.StrokeWidth = 5;
- paint.SetStyle(Paint.Style.Stroke);
- paint.Color = global::Android.Graphics.Color.White;
- canvas.DrawPath(path, paint);
- paint.Dispose();
- path.Dispose();
- return result;
- } catch (Exception ex) {
- var msg = ex.Message;
- }
- return base.DrawChild(canvas, child, drawingTime);
- }
- }
- }
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.iOS
In iOS project, create a class name:
ImageCircleRenderer.cs
- using System;
- using System.ComponentModel;
- using System.Diagnostics;
- using ImageCircle.CustomControls;
- using ImageCircle.iOS.CustomControls;
- using Xamarin.Forms;
- using Xamarin.Forms.Platform.iOS;
- [assembly: ExportRenderer(typeof(ImageCircle), typeof(ImageCircleRenderer))]
- namespace ImageCircle.iOS.CustomControls {
- public class ImageCircleRenderer: ImageRenderer {
- protected override void OnElementChanged(ElementChangedEventArgs<Image> e) {
- base.OnElementChanged(e);
- if (e.OldElement != null || Element == null) return;
- CreateCircle();
- }
- protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) {
- base.OnElementPropertyChanged(sender, e);
- if (e.PropertyName == VisualElement.HeightProperty.PropertyName || PropertyName == VisualElement.WidthProperty.PropertyName) {
- CreateCircle();
- }
- }
- private void CreateCircle() {
- try {
- double min = Math.Min(Element.Width, Element.Height);
- Controls.Layer.CornerRadius = (float)(min / 2.0);
- Controls.Layer.MasksToBounds = false;
- Controls.Layer.BorderColor = Color.White.ToCGColor();
- Controls.Layer.BorderWidth = 1;
- Controls.ClipsToBounds = true;
- } catch (Exception ex) {
- WriteLine("Unable to create circle image: " + ex);
- }
- }
- }
- }
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:
Please download the sample from here