Search code examples
xamarin.formscustom-renderer

Xamarin Forms native customrenderer


I have followed James Montemagno's guide on how to make a custom renderer for round images in my Xamarin Forms Shared Project.

https://blog.xamarin.com/elegant-circle-images-in-xamarin-forms/

(being a true copy of the guide it feels redundant to actually add the code itself to my project but please comment if that is not the case)

It is working flawless, however, I need to change the colour of the circle border dynamically with the press of a button when the app is running.

But since the colour of the circle is set natively in each renderer I am uncertain how I could possibly change it from my shared code.


Solution

  • Maybe this snippet can help:

    public class CircleImage : Image
    {
    
        public static readonly BindableProperty CurvedBackgroundColorProperty =
            BindableProperty.Create(
                nameof(CurvedBackgroundColor),
                typeof(Color),
                typeof(CurvedCornersLabel),
                Color.Default);
    
        public Color CurvedBackgroundColor
        {
            get { return (Color)GetValue(CurvedBackgroundColorProperty); }
            set { SetValue(CurvedBackgroundColorProperty, value); }
        }
    
    }
    
    //Android/iOS
    
    [assembly: ExportRenderer(typeof(CircleImage), typeof(CircleImageRenderer))]
    namespace SchedulingTool.iOS.Renderers
    {
        public class CircleImageRenderer : ImageRenderer
        {
            protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
            {
                base.OnElementChanged(e);
    
                if (e.NewElement != null)
                {
                    var xfViewReference = (CircleImage)Element;
                    //Here you can reference xfViewReference.CurvedBackgroundColor to assign what ever is binded.
                }
            }
        }
    }
    

    I hope you get the main idea, you can create your own bindable properties and access them on the Native Renderer.

    If everything does not go as expected you can always download the NuGet (which has everything you need):

    https://github.com/jamesmontemagno/ImageCirclePlugin