XAML File
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:customImage="clr-namespace:CircleImagePRoject" x:Class="CircleImagePRoject.MainPage"> <StackLayout VerticalOptions="Center"> <Label Text="Create Circle Image Using Xamarin Form" HorizontalOptions="Center" ></Label> <Image Source="Users" HorizontalOptions="Center" VerticalOptions="Center" HeightRequest="80" WidthRequest="80"></Image> <customImage:CircleImageRenderer Source="Users" HorizontalOptions="Center" VerticalOptions="Center" HeightRequest="80" WidthRequest="80" ></customImage:CircleImageRenderer> </StackLayout> </ContentPage>
In a Xamarin.Forms Project Create Renderer
CircleImageRenderer.cs
using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; namespace CircleImagePRoject { public class CircleImageRenderer:Image { } }
Xamarin Android Renderer
CircleImage.cs
using System; using Android.Content; using Android.Graphics; using CircleImagePRoject; using CircleImagePRoject.Droid; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(CircleImageRenderer), typeof(CircleImage))] namespace CircleImagePRoject.Droid { class CircleImage : ImageRenderer { public CircleImage(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Image> e) { base.OnElementChanged(e); if (e.OldElement == null) { if ((int)Android.OS.Build.VERSION.SdkInt < 18) { SetLayerType(Android.Views.LayerType.Software, null); } } } protected override bool DrawChild(Canvas canvas, Android.Views.View child, long drawingTime) { try { var radius = Math.Min(Width, Height) / 2; var strokeWidth = 10; radius -= strokeWidth / 2; //Create path to clip var 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(); // Create path for circle border 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); //Properly dispose paint.Dispose(); path.Dispose(); return result; } catch (Exception ex) { // Debug.WriteLine("Unable to create circle image: " + ex); } return base.DrawChild(canvas, child, drawingTime); } } }
No comments:
Post a Comment