Tag Archives: Udara Alwis

Publishing the Nuget of my Color Picker Control for Xamarin.Forms!

Let me share the journey of me publishing the Nuget Package of my interactive Color Picker Control for Xamarin.Forms that I built using SkiaSharp.

So some time back I built an Interactive and responsive Color Picker Control for Xamarin.Forms (Android, iOS, UWP) with a whole bunch of awesome features. On a Canvas with a beautiful Color spectrum similar to a rainbow gradient effect spreading across, drag, drop, swipe and pan over the Canvas to pick the Color you need easily, in a fun-to-use interactive experience. Built from pure Xamarin.Forms based on SkiaSharp, lightweight and fast!

Backstory…

In my previous blog post I shared with you guys how I built my interactive Color Picker Control for Xamarin.Forms, https://theconfuzedsourcecode.wordpress.com/2020/02/26/i-built-an-interactive-color-picker-control-for-xamarin-forms/

Since then I had been adding a whole bunch of extra feature to this Color Picker Control I built, so I thought it was a good idea to publish it as a Nuget Package and share with everyone! 😀

So this time, let me share my journey of implementing more advanced features and publishing the Nuget Package of my Color Picker Control for Xamarin.Forms! 😉

Some thought…

So before I isolated my Color Picker Control into a stand alone reusable package, I wanted to make sure that I maintain my philosophy of building Plugins. This would definitely have a big impact on your Users who will will be using these Plugins to build their apps, therefore I’ll share the tick list that I consider as important as follows…

Plug and Play: The plugin should easy to set up with. Do not force Devs to set up any dependencies or property values by themselves. The properties and behaviors of the Plugin should have default values assigned to them.

Customization: It should be easy and straight forward for the Devs to customize the appearance or the behaviors of the Plugin. In some case this might be limited, but you must build the Plugin in a way it make it easy as much as possible.

Embedded: In the case of UI Element Plugins, you should make it easy to be embedded into any Layout structure, being able to inherit the Parent Layout’s behaviors and values, without overriding or disrupting them.

Keep it Light: Make the Plugin as lightweight as possible, give the Dev the chance to choose which assemblies to be included in the plugin. Remove unnecessary references or dependencies from your Plugin core, so it’s light weight as possible.

Performance First: It shouldn’t cause any performance bottleneck, therefore from scratch you must build the Plugin with performance in mind. Constantly check for performance improvements during the development of your Plugin.

So may be go over this list before you build or release a Plugin for the public! 😉 Alright, with all those principles in mind, let’s move ahead…

The Features!

So here are the features that are already available in the Color Picker Control that I built which I had shared from my previous blog post…

  • Picked Color: The Property that allows Users to retrieve the Color values that’s selected from the Color Picker. This value is only a Get Property.
  • Picked Color Changed Event: The Event that fires up every time the PickedColor Value is changed during Color selection. You can subscribe to this event and observe the behavior.

Since my venture into this Color Picker Plugin I had a few ideas in mind as improvements or rather add as extra features, rather than just being a UI Element which allows you to pick a color on a beautiful spectrum! 😉 So here are the extra features that I’ll be building up into it..

  • Change the Available Base Colors List: You can set the primary list of Colors where the gradient spectrum will be rendered from. So choose the base colors you want to be populated as you wish and it will be rendered on the Color Picker.
  • Change the Color List Flow Direction: You will be able to change the direction of the flow of the colors on the canvas, where it be Horizontal flow or a Vertical flow of the color spectrum. Further more Horizontally being starting off the flow from left to right, and Vertically being top to bottom.
  • Change the Color Spectrum Style: You will be able to change the style of the Color Spectrum gradient, the rendering combination of base colors (Hue), or lighter colors (Tint) or darker colors (Shade). You’ll be able to set it with different order as well, ex: Hue Colors, Shade Colors, Tint Colors or Tint Colors, Hue Colors, Shade Colors, etc..
  • Change the Appearance of the Pointer: The white color circle that is used as the Picker Pointer on the Canvas, should be able to customized based on its Diameter or Thickness of the Circle border. Another nice addition would be to allow user to set the position of the Pointer as they wish.

Alright, now that we listed down the new intended feature set that I’m planning to ship out with my Color Picker Control, let’s get down to building it… 😀

Sneak Peek!

Just to give a little glimpse of the awesomeness I ended up building and publishing… 😀 behold the Color Picker Control for Xamarin.Forms!

Pretty awesome eh! 😉 I have moved out of my previous repo to a new standalone repo in github, since I’m publishing this as a package. Therefore all the new development will be done in this repository.

Project hosted on github:
https://github.com/UdaraAlwis/XFColorPickerControl

So feel free to take a look in there before we continue… 😉

Time to Build!

Since I already explained in my previous blog post how I built my Color Picker Control from scratch step by step, I won’t be repeatedly going through same code bits in this post, but rather focus on the new changes and features only.
If you haven’t read that one yet, then I would recommend you take a peek there first, I built an Interactive Color Picker Control for Xamarin.Forms! And continue here…

I named the Solution as Udara.Plugin.XFColorPickerControl, and in return I intend to keep the Package reference with the same naming. I am using Visual Studio 2019 on Windows 10 here as my development environment.

I have created a VS Solution with a .NET Standard 2.0 Library which will hold the UI Control in place, with the naming ColorPicker. You can see I have added the dependencies of the Plugin, with Xamarin.Forms and SkiaSharp.Views.Forms packages. 😉

Notice the pure Xamarin.Forms DemoApp project inside the Demo folder that I have added to the same solution? That is for testing and showcasing the Plugin’s use, also as a reference point for anyone who wants to learn how to use the Plugin in many different ways, this attached DemoApp could come handy. 😀

The ColorPicker.xaml is the UI Element that users will be using under the namespace Udara.Plugin.XFColorPickerControl.ColorPicker in their XAML or C# code for building the UI. Here’s base skeleton implementation of the ColorPicker.xaml.cs, which all the core implementation will be taking place…

namespace Udara.Plugin.XFColorPickerControl
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ColorPicker : ContentView
    {
        public ColorPicker()
        {
            InitializeComponent();
        }

        // Implementation goes here
    }
}

Next let’s get into the implementation of Features one by one as I discussed before…

Building the Features!

So I’m going to use the same code for the two features that I already implemented in my previous blog post, Picked Color and Picked Color Changed Event feature that’s represented by PickedColor Property and PickedColorChanged Event Handler.

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ColorPicker : ContentView
{
	/// <summary>
	/// Occurs when the Picked Color changes
	/// </summary>
	public event EventHandler<Color> PickedColorChanged;

	public static readonly BindableProperty PickedColorProperty
		= BindableProperty.Create(
			nameof(PickedColor),
			typeof(Color),
			typeof(ColorPicker));

	/// <summary>
	/// Get the current Picked Color
	/// </summary>
	public Color PickedColor
	{
		get { return (Color)GetValue(PickedColorProperty); }
		private set { SetValue(PickedColorProperty, value); }
	}
	
	...
}

Now considering the rest of the features that I discussed in the beginning, all those features can be implemented and exposed via Bendable Properties, and handling the Property Changed events internally to react for any changes requested during run time.

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ColorPicker : ContentView
{
    ...
 
    public static readonly BindableProperty PropertyNameProperty
        = BindableProperty.Create( 
        ... 
        
            validateValue: (bindable, value) =>
            {
                // validate value
                return (..);
            },
            
            propertyChanged: (bindable, value, newValue) =>
            {
                if (newValue != null)
                    // action on value change
                else
                    // handling null values
                    ((ColorPicker)bindable).PropertyNameProperty = default;
            });
        );
 
    public type PropertyName
    { ... }
 
    ...
}

All the Bindable Properties are safeguarded with validations as you see above. I have added an extra layer of protection against unnecessary null values being set up, by defaulting the property value to default of itself. You can check the full implementation of each of these Properties on the github repo itself. github.com/UdaraAlwis/XFColorPickerControl Let’s begin..

Feature: BaseColorList

Bindable Property, BaseColorList: Change the available base Colors on the Color Spectrum, of the Color Picker. This will take a List of strings of Color names or Hex values, which is held in an IEnumerable as show here, also I have set up the fallback default values with the rainbow color spectrum.

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ColorPicker : ContentView
{
    ...

    public static readonly BindableProperty BaseColorListProperty
        = BindableProperty.Create( ... );

    public IEnumerable BaseColorList
    { ... }

    ...
}

This Property is then consumed during the SkiaSharp rendering cycle as follows, where as we’re using the Xamarin.Forms built in ColorTypeConverter to parse the string color values to actual Color objects and then to SKColor objects, which is then used to render the render the color spectrum on the Color Picker Control. 😀

...
    private void SkCanvasView_OnPaintSurface
                   (object sender, SKPaintSurfaceEventArgs  e)
    {
        ...
         
        // Draw gradient rainbow Color spectrum
        using (var paint = new SKPaint())
        {
            paint.IsAntialias = true;
 
            // Initiate the base Color list
            ColorTypeConverter converter = new ColorTypeConverter();
            System.Collections.Generic.List<SKColor> colors = 
                new System.Collections.Generic.List<SKColor>();
            foreach (var color in BaseColorList)
                colors.Add(((Color)converter.
		          ConvertFromInvariantString(color.ToString())).ToSKColor());
				
            ...
        }
    }
...

Pretty straight forward eh! Let’s see how you could use this as a developer.

How to use?

You can easily use this feature in XAML as follows, by accessing ColorPicker.BaseColorList property and setting up the list of color values you prefer as hex values or with pre-defined color value names.

<xfColorPickerControl:ColorPicker
	x:Name="ColorPicker"
	...	>
	<xfColorPickerControl:ColorPicker.BaseColorList>
		<x:Array Type="{x:Type x:String}">
			<!--  Yellow  -->
			<x:String>#ffff00</x:String>
			<!--  Aqua  -->
			<x:String>#00ffff</x:String>
			<!--  Fuchsia  -->
			<x:String>#ff00ff</x:String>
			<!--  Yellow  -->
			<x:String>#ffff00</x:String>
		</x:Array>
	</xfColorPickerControl:ColorPicker.BaseColorList>
</xfColorPickerControl:ColorPicker>

If you prefer in C# code, you can easily do as as well, a list of string values of the colors…

ColorPicker.BaseColorList = new List<string>()
{
	"#00bfff",
	"#0040ff",
	"#8000ff",
	"#ff00ff",
	"#ff0000",
};

Here’s some action…

Feature: ColorFlowDirection

The Bindable Property, ColorFlowDirection: Change the direction in which the Colors are flowing through on the Color Spectrum, of the Color Picker. This will allow you to set whether the Colors are flowing through from left to right, Horizontally or top to bottom, Vertically. I have defined an Enum type which will represent this type of course.

namespace Udara.Plugin.XFColorPickerControl
{
    public enum ColorFlowDirection
    {
        Horizontal,
        Vertical
    }
}

Let’s create our ColorFlowDirection Bindable Property based on that,

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ColorPicker : ContentView
{
    ...

    public static readonly BindableProperty ColorFlowDirectionProperty
        = BindableProperty.Create( ... );

    public ColorFlowDirection ColorFlowDirection
    { ... }

    ...
}

The default value will be set as ColorFlowDirection.Horizontal, and if the User changes value during run time, it will fire up a new SkiaSharp rendering cycle of the Canvas, effectively rendering the spectrum accordingly to the new color value, which is handled in the rendering logic as below…

...
    private void SkCanvasView_OnPaintSurface
                   (object sender, SKPaintSurfaceEventArgs  e)
    {
        ...
        
            // create the gradient shader between base Colors
            using (var shader = SKShader.CreateLinearGradient(
                new SKPoint(0, 0),
                ColorFlowDirection == ColorFlowDirection.Horizontal ?
                    new SKPoint(skCanvasWidth, 0) : 
                    new SKPoint(0, skCanvasHeight),
                colors.ToArray(),
                null,
                SKShaderTileMode.Clamp))
            {
                paint.Shader = shader;
                skCanvas.DrawPaint(paint);
            }
            
        ...
    }
...

The trick here is to configure the SKShader.CreateLinearGradient() method’s start and end coordinate parameters, which governs the direction in which the gradient effect will be drawn with the list of colors, thus rendering the color list from left to right or top to bottom. As you can see for Horizontal effect, we use SKPoint (0,0) to SKPoint(<canvasWidth>, 0) by using the corner most value on the X axis for the end coordinates, the same pattern is used for Vertical effect with bottom most value on the Y axis.

Here how to consume this feature as a developer…

How to use?

You can easily use this feature in XAML, by accessing ColorPicker.ColorFlowDirection property and setting Horizontal or Vertical option as you prefer…

<xfColorPickerControl:ColorPicker
	x:Name="ColorPicker"
	ColorFlowDirection="Horizontal"
	...	>
</xfColorPickerControl:ColorPicker>

If you prefer in C# code, use the ColorFlowDirection.Horizontal or Vertical option…

ColorPicker.ColorFlowDirection =
	Udara.Plugin.XFColorPickerControl.ColorFlowDirection.Horizontal;

Here’s some action…

Feature: ColorSpectrumStyle

The Bindable Property, ColorSpectrumStyle: Change the Color Spectrum gradient style, with the rendering combination of base colors (Hue), or lighter colors (Tint) or darker colors (Shade). If you’re not familiar with these technical terms, here’s a clear illustration of comparison of Hue, Shade, and Tint of Colors.

We need to make sure our Color Picker is able to deliver to this kind of requirement, having darker or lighter colors of the given base colors on the Color Picker Spectrum. So I’ve created an Enum type which will consist of all the possible combinations of Hue, Shade and Tint colors based on the available Base Colors, that would facilitate this feature.

namespace Udara.Plugin.XFColorPickerControl
{
    public enum ColorSpectrumStyle
    {
        HueOnlyStyle,
        HueToShadeStyle,
        ShadeToHueStyle,
        HueToTintStyle,
        TintToHueStyle,
        TintToHueToShadeStyle,
        ShadeToHueToTintStyle
    }
}

Let’s create our ColorSpectrumStyle Bindable Property based on that,

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ColorPicker : ContentView
{
    ...

    public static readonly BindableProperty ColorSpectrumStyleProperty
        = BindableProperty.Create( ... );

    public ColorSpectrumStyle ColorSpectrumStyle
    { ... }

    ...
}

I will be setting ColorSpectrumStyle.HueToShadeStyle as the default value for this property, any changes to this value during run time will kick start a new refresh draw on the Color Spectrum, which is handled in the rendering logic as below…

...
    private void SkCanvasView_OnPaintSurface
                   (object sender, SKPaintSurfaceEventArgs  e)
    {
        ...
         
        // Draw secondary gradient color spectrum
        using (var paint = new SKPaint())
        {
            paint.IsAntialias = true;
 
            // Initiate gradient color spectrum style layer
            var colors = GetSecondaryLayerColors(ColorSpectrumStyle);
			
            ...
        }
    }
...

Over here, we’re retrieving the list of colors based on the ColorSpectrumStyle value, which is a combination of Transparent, Black and White colors, which will be used to draw the secondary gradient layer. GetSecondaryLayerColors() will be returning the appropriate list of secondary colors that matches the ColorSpectrumStyle requested as follows.

...
    private SKColor[] GetSecondaryLayerColors(ColorSpectrumStyle colorSpectrumStyle)
    {
        ...
        
        if (colorSpectrumStyle == GradientColorStyle.DarkToColorsToLightStyle)
        {
            return new SKColor[]
            {
                SKColors.Black,
                SKColors.Transparent,
                SKColors.White
            };
        }
        
        ...
    }
...

I’m maintaining a simple If-else block chain which will check for the ColorSpectrumStyle value available and return the appropriate list of colors back. Quite straight forward! 😉

Now here’s how you use this awesome feature…

How to use?

You can easily use this feature in XAML, by accessing ColorPicker.ColorSpectrumStyle property and setting the appropriate Style option as you prefer…

<xfColorPickerControl:ColorPicker
	x:Name="ColorPicker"
	ColorSpectrumStyle="TintToHueToShadeStyle"
	...	>
</xfColorPickerControl:ColorPicker>

If you prefer in C# code…

ColorPicker.ColorSpectrumStyle =
	Udara.Plugin.XFColorPickerControl.ColorSpectrumStyle.TintToHueToShadeStyle;

Here’s some action…

Feature: PointerRing Styling

As you can see there’s a pretty neat Pointer Ring that’s pointing the picked color position on the Color Picker, it would be nice to be able to customized this too eh! 😉

Therefore I have introduced four features for this,

  • PointerRingDiameterUnits
  • PointerRingBorderUnits
  • PointerRingPositionXUnits
  • PointerRingPositionYUnits

Alright, let’s walk through them one by one..

Feature: PointerRingDiameterUnits

The Bindable Property, PointerRingDiameter: Changes the Diameter size of the Pointer Ring on the Color Picker. It accepts values between 0 and 1, as a representation of numerical units which is compared to the 1/10th of the longest length of the Color Picker Canvas. By default this value is set to 0.6 units.

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ColorPicker : ContentView
{
    ...
 
    public static readonly BindableProperty PointerRingDiameterUnitsProperty
        = BindableProperty.Create( ... );
 
    public double PointerRingDiameterUnits
    { ... }
    
    ...
}

This will be calculated against the longest length of Color Picker’s Canvas, whether it be Width or Height. The reason for adding another 1/10th of the value is to maintain the maximum size of the Pointer Ring, avoiding ridiculous sizing of the element. lol So the Precise calculation is as, Canvas Size (Height or Width) x PointerRingDiameterUnits x (1/10)
This value will render exactly to the same proportion against different screen sizes and DPs.

...
    private void SkCanvasView_OnPaintSurface
                   (object sender, SKPaintSurfaceEventArgs  e)
    {
        ...
         
        // Painting the Touch point
        using (var paint = new SKPaint())
        {
            ...
 
            var canvasLongestLength = (skCanvasWidth > skCanvasHeight) 
                    ? skCanvasWidth : skCanvasHeight;

            // Calculate 1/10th of the units value for scaling
            var pointerRingDiameterUnitsScaled = (float)PointerRingDiameterUnits / 10f;
            // Calculate against Longest Length of Canvas 
            var pointerRingDiameter = (float)canvasLongestLength 
                                                    * pointerRingDiameterUnitsScaled;

            // Outer circle of the Pointer (Ring)
            skCanvas.DrawCircle(
                _lastTouchPoint.X,
                _lastTouchPoint.Y,
                (pointerRingDiameter / 2), paintTouchPoint);

            ...
        }
    }
...

I’ve set up the skCanvas.DrawCircle() with the (pointerRingDiameter / 2) since it accepts radius value only for drawing the circle.

How to use?

You can easily use this feature in XAML, by accessing ColorPicker.PointerRingDiameterUnits property and setting the value against your Color Picker’s Width and Height.

<xfColorPickerControl:ColorPicker
    x:Name="ColorPicker"
    PointerRingDiameterUnits="0.6"
    ...    >
</xfColorPickerControl:ColorPicker>

If you prefer in C# code…

ColorPicker.PointerRingDiameterUnits = 0.6;

Here’s some action…

Feature: PointerRingBorderUnits

The Bindable Property, PointerRingBorderUnits: Changes the Border Thickness size of the Pointer Ring on the Color Picker. It accepts values between 0 and 1, as a representation of numerical units which is calculated against the diameter of the Pointer Ring. By default this value is set to 0.3 units.

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ColorPicker : ContentView
{
    ...
 
    public static readonly BindableProperty PointerRingBorderUnitsProperty
        = BindableProperty.Create( ... );
 
    public double PointerRingBorderUnits
    { ... }
    
    ...
}

This calculation executes against the Pointer Ring’s pixel diameter value as, (Pointer Ring Diameter in Pixels) x PointerRingBorderUnits, since this is dependent on the Pointer Ring’s diameter, we thickens the border inside that circle only. Basic technique here is to draw a Circle inside the Parent Circle, with the picked pixel point’s color, emulating the visual of a Ring.

...
    private void SkCanvasView_OnPaintSurface
                   (object sender, SKPaintSurfaceEventArgs  e)
    {
        ...
         
        // Painting the Touch point
        using (var paint = new SKPaint())
        {
            ...
 
            // Draw inner circle with picked color
            paintTouchPoint.Color = touchPointColor;

            // Calculate against Pointer Circle
            var pointerRingInnerCircleDiameter 
                          = (float)pointerRingDiameter 
                              * (float)PointerRingBorderUnits; 

            // Inner circle of the Pointer (Ring)
            skCanvas.DrawCircle(
                _lastTouchPoint.X,
                _lastTouchPoint.Y,
                ((pointerRingDiameter 
                        - pointerRingInnerCircleDiameter) / 2), paintTouchPoint);
            ...
        }
    }
...

I’ve set up the skCanvas.DrawCircle() with the calculation, ((pointerRingDiameter – pointerRingInnerCircleDiameter) / 2) since it accepts radius value only for drawing the circle.

How to use?

You can easily use this feature in XAML, by accessing ColorPicker.PointerRingBorderUnits property and setting the value against PointerRingDiameterUnits you have used.

<xfColorPickerControl:ColorPicker
    x:Name="ColorPicker"
    PointerRingBorderUnits="0.3"
    ...    >
</xfColorPickerControl:ColorPicker>

If you prefer in C# code…

ColorPicker.PointerRingBorderUnits = 0.3;

Here’s some action…

Feature: PointerRingPosition<X,Y>Units

The Bindable Property, PointerRingPosition<X,Y>Units: Changes the Pointer Ring’s position on the Color Picker Canvas programmatically. There are of two bindable properties PointerRingPositionXUnits and PointerRingPositionYUnits, which represents X and Y coordinates on the Color Picker Canvas. It accepts values between 0 and 1, as a presentation of numerical units which is calculated against the Color Picker Canvas’s actual pixel Width and Height. By default both the values are set to 0.5 units, which positions the Pointer Ring in the center of the Color Picker.

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ColorPicker : ContentView
{
    ...
 
    public static readonly BindableProperty PointerRingPositionXUnitsProperty
        = BindableProperty.Create( ... );
 
    public double PointerRingPositionXUnits
    { ... }
	
    public static readonly BindableProperty PointerRingPositionYUnitsProperty
        = BindableProperty.Create( ... );
 
    public double PointerRingPositionYUnits
    { ... }
 
    ...
}

This calculation executes against the Color Picker Canvas’s actual pixel Width and Height as, (Color Picker Canvas Width in Pixels) x PointerRingPositionXUnits and (Color Picker Canvas Height in Pixels) x PointerRingPositionYUnits
Up on invoke of the PropertyChanged on those Properties, we make a call to the following SetPointerRingPosition() with the new X and Y position units requested from User.

...
    private void SetPointerRingPosition
                      (double xPositionUnits, double yPositionUnits)
    {
        // Calculate actual X Position
        var xPosition = SkCanvasView.CanvasSize.Width
                                 * xPositionUnits; 
        // Calculate actual Y Position
        var yPosition = SkCanvasView.CanvasSize.Height
                                 * yPositionUnits; 

        // Update as last touch Position on Canvas
        _lastTouchPoint = new SKPoint(Convert.ToSingle(xPosition), Convert.ToSingle(yPosition));
        SkCanvasView.InvalidateSurface();
    }
...

We’re calculating the actual X and Y coordinates against the Canvas pixel size and setting up the _lastTouchPoint with those values, for keeping the Pointer Ring position on canvas in sync with touch inputs positioning and programmatical positioning, then at the end we fire up the SkiaSharp rendering cycle with SkCanvasView.InvalidateSurface();

Handling Pointer Ring Position on Initialization!

We need to handle the positioning of the Pointer Ring on the initialisation or on the rendering of the element during run time. We can achieve this by a one-time execution with a boolean flag, that executes this logic. So upon the first SkiaSharp canvas rendering cycle, we hook up to the PointerRingPositionXUnits and PointerRingPositionYUnits properties and render the Pointer Ring Position to the set value.

...    
    private bool _checkPointerInitPositionDone = false;

...
    private void SkCanvasView_OnPaintSurface
                   (object sender, SKPaintSurfaceEventArgs  e)
    {
        ...
          
        if (!_checkPointerInitPositionDone)
        {
            var x = ((float)skCanvasWidth * (float)PointerRingPositionXUnits);
            var y = ((float)skCanvasHeight * (float)PointerRingPositionYUnits);

            _lastTouchPoint = new SKPoint(x, y);

            _checkPointerInitPositionDone = true;
        }
    }
...

We use _lastTouchPoint variable which is used by the drawing functions for rendering the Pointer Ring on Color Picker’s Canvas.

How to use?

You can easily use this feature in XAML, by accessing ColorPicker.PointerRingPositionXUnits property and ColorPicker.PointerRingPositionYUnits setting the values against your Color Picker’s Width and Height.

<xfColorPickerControl:ColorPicker
    x:Name="ColorPicker"
    PointerRingPositionXUnits="0.3"
    PointerRingPositionYUnits="0.7"
    ...    >
</xfColorPickerControl:ColorPicker>

If you prefer in C# code…

ColorPicker.PointerRingPositionXUnits = 0.3;
ColorPicker.PointerRingPositionYUnits = 0.7;

Here’s some action…

UWP Bug Fix!

One issue I noticed was on UWP run time, where the SkiaSharp’s Canvas touch event behaves differently than iOS and Android. The touch event would get activated even if you hover over the canvas using your mouse pointer, and this was causing the PickedColor property to fire up.
The Touch event should occur only if you actually click on the canvas and drag and drop on the Canvas, so in order to fix this I used the InContact property SKTouchEventArgs inside the touch event to validate on UWP run time.

...
    private void SkCanvasView_OnTouch
                (object sender, SKTouchEventArgs e)
    {
        // to fix the UWP touch behavior
        if (Device.RuntimePlatform == Device.UWP)
        {
            // avoid mouse over touch events
            if (!e.InContact)
                return;
        }

        _lastTouchPoint = e.Location;
        
        ...
    }
...

This fixed the bug on UWP, making sure the touch event is validated before executing the rest of the logic.

Nugetizing!

Alright then, its time to set up our beautiful Color Picker Control for Xamarin.Forms as a Nuget Package using Visual Studio. I’m going first set the Nuget package properties first, then build the package, and finally publish it to Nuget, allowing it to be shared with everyone out there! 😀

Set up package properties…

You could do this straight from Visual Studio Project Properties, or directly from a Nuspec file added to the project itself. For now I would prefer setting up properties in VS Project -> Properties – Package tab, making sure to add all the necessary properties and information about the package as shown below…

Make sure to click on “Generate Nuget package on build” tick, which will enable all the property fields. You could also do this by editing .csproj file of the package project as well, if you require any fine tuned editing…

Now we’re ready to build the package of our Udara.Plugin.XFColorPicker library.

Building the Package…

We need to create the Publish Profile for the package.
Right click on Library project node -> Publish

If this was your first time, it will navigate you to create new Publish Profile tab as shown below…

It is easier to set up a Publish Profile, since you don’t have to manually change your build configuration to Release and then launch a build. Therefore I have set it up now, and next time I publish it will straightaway handle all the configuration for you! 😀

Click Publish, and it nicely builds…

Once we navigate to the folder location mentioned in the above build output…

There we have our nupkg package file, which we can then use to directly upload to Nuget!

Upload to Nuget…

Grab that nupkg file and drag and drop into the upload page of nuget.org and you’re done!

Here you’ll be able to add a short marked down documentation for the users, I would highly recommend you do that since it will increase the support and visibility.

Well that’s all it takes, and the package will be available in a few hours on Nuget!

Updating Package…

Now how do we update our package? if you have noticed around nuget, there’s no update option in in the page where you manage the package. You can update your package by using the NuGet command-line utility or directly uploading an increment build, in which I have opted for the end option to keep it easy.

So when you want to push an update to your package, make sure to update the package properties in Visual Studio to reflect the next immediate version, as shown below where I’m updating from version 1.0.2 to version 1.0.3…

Also do no forget the assembly versioning as well…

Now build your package and directly go to nuget upload page, drag and drop the file…

Make sure to add the nuget documentation and Submit!

Done and dusted, just like that, the updating is done! 😀

Published on nuget:
nuget.org/Udara.Plugin.XFColorPickerControl/

Now anyone can use my Color Picker Control for Xamarin.Forms by setting up this nuget package in their project…

Demoing it up!

As you saw at the beginning I have attached a Demo project into the same parent Solution of Udara.Plugin.XFColorPickerControl, which I have used for testing during development, and to maintain as a demonstration of all the awesome features this plugin provides! 😉

Since this plugin is meant to be compatible on a cross platform environment its impeccable do continuous testing on all the platforms. Anyhow here’s a sneak peek of the demo app…

I have created separate pages to demonstrate awesomeness of each special feature…

BaseColorList Demo:

Android, UWP and iOS…

ColorFlowDirection Demo:

Android, UWP and iOS…

ColorSpectrumStyle Demo:

Android, UWP and iOS…

PointerRingStyling Demo:

Android, UWP and iOS…

Since it’s a pure Xamarin.Forms and can be deployed directly to all three platforms, Android, iOS and Windows UWP, you can do the same with my plugin. Feel free to take a look at the demo app in case if you need trouble shooting.

Conclusion!

There you have it my Color Picker Control for Xamarin.Forms, now published to nuget as a package, with a whole bunch of awesome features, and anyone can easily use it in their own Xamarin.Forms projects! 😀 Pheww… What a joy! Sharing something you’ve been working so hard for a long time. So feel free to give a try, contribute, and any feedback is always welcome…

hosted on github:
github.com/UdaraAlwis/XFColorPickerControl

published on nuget:
nuget.org/Udara.Plugin.XFColorPickerControl/

Well that was fun! So keep in mind I’m going to be implementing more and more features for this plugin in future, and might end up changing some of those features or implementations as well. This blog post will not be constantly updated against them, so many sure to keep in touch with the docs in the github repo itself for future references.

Imagination is the limit yol! 😉

Share the love! 😀 Cheers!

UPDATE: Guess what yol? My little Color Picker Control got featured at the .NET Conf: Focus on Xamarin event by Microsoft!

WOOT! WOOT! Thanks @James Montemagno!

I’m building an Atom Simulation with SkiaSharp and Xamarin.Forms!

So lately I’ve been on quite a bunch of adventures with SkiaSharp in Xamarin.Forms! 😀 You know how it is for me, pushing the limits of the framework as usual for the fun 😉 And this right here is one of those adventures I’m going to share with you all…

Little Backstory…

I’ve always been fascinated by the Atom’s graphical structure being the science nerd back in school days. I’ve always loved the simulation of the Electrons circulating around the atom’s core filled with Neutrons and Protons. 😀 So while reminiscing those memories, I was thinking of ways to play around with SkiaSharp framework, and suddenly, AHA! A light bulb lit-up on my head! 😀

I’ve decided to build an Atom Simulation in SkiaSharp, with Xamarin.Forms! 😉

A sneak peek!

  

TADAAA! 😀

So where is it going?

Haven’t you ever thought those animated atom structure simulation they show on TV was very very cool? Well I’m thinking of building a similar simulation with SkiaSharp on top of Xamarin.Forms! 😀

And this is going to be a step by step process, where I shall begin with the basic 2D structure and slowly moving towards the complex animated simulation!

Well I’ve already started developing this some time back, and I’ve made quite a bit of progress.

I have hosted this on Github: github.com/UdaraAlwis/SkiaSharpAtomStructureSo that anyone can try it out or add improvements to it, and yes I’m open for pull requests! 😉

Code behind tech bits?

Well basically as you may have already figured out, it’s a Xamarin.Forms project, and I’m using the awesome SkiaSharp for rendering the graphics.

And to be specific with SkiaSharp I’m using the following to render the cool stuff:

  • 2D Shapes Drawing
  • Canvas Translations and Rotations
  • Continuous Animation Rendering
  • Gradient Shading
  • Touch handling

Pretty cool set of features right there, out of the box with SkiaSharp eh! 😉

Progress so far…

I’ve broken the progressive steps to several Pages in the project for clear distinction between the code behind.

I will be updating this post as the project moves forward with improvements and new progression steps.

And here they are…

1. Atom Silhouette

 

So the first step was to simply build a silhouette of the atom structure. There you have the core with Neutrons and Protons, and the Electrons around it in their own orbits.

Basically I’m using the SkCanvas.DrawCircle() to draw the center core and then SkCanvas.DrawOval() to draw the Oval Orbits around the core. 😉

Then I’m drawing the “Electron dot” for each orbit using the corner most point of the Oval Orbit, which is basically the width of the Oval. Tricky yeah!

You might think how about the angles of the oval? Oh yeah I’m using Canvas Rotation for each orbit draw cycle, SkCanvas.RotateDegrees(xx degrees)! 😀

And there’s a simple +/- increment mechanism for increasing and decreasing the number of electrons around the orbit!

You can take a look at the implementation: AtomSilhouettePage.xaml.cs

2. Atom Orbital Paths

 

Here’s a little improvement for the previous step, where as I’ve added some gradient effect for the drawing of the Oval path with the same SkCanvas.DrawOval() call.

The CreateSweepGradient() is one of the way to create a gradient color effect in SkiaSharp, whereas we’ve used white and dark gray as the color here.

Oh Gradients are always cool yeah! 😉

You can take a look at the implementation: AtomOrbitalPathsPage.xaml.cs

3. Atom Orbital Paths Uneven

 

Now we know in reality the Atom’s electron orbit is not a nice even orbit, so we’re going to reflect just that in this progress step! 😀

So basically I’m randomly generating the Oval’s supposed width for each orbit, thus giving the above output!

You can take a look at the implementation: AtomOrbitalPathsUnevenPage.xaml.cs

4. Atom Animated Silhouette

 

This is the step where I kick it up a notch, with the Animation rendering using SkiaSharp!

So as we all know there’s no direct animation rendering support with SkiaSharp, since its a on demand 2D vector graphics rendering system.

What I’m doing here to get the electron dot’s to movement on the oval orbit, is I’m rendering it’s each 360 degrees positions continuously on a timer loop. Might sound pretty complex, but its actually simple! 😉

You can take a look at the implementation: AtomAnimatedPage.xaml.cs

5. A cool touch feature!

I’ve added something cool for the number of displayed Electron’s incremental mechanism!

 

I’ve added a touch handling feature to the atom’s electron incremental mechanism, so now basically you can swipe up or down the screen to increase or decrease the number of electron orbits of the Atom! 😉 Now instead of clicking on the +/- buttons, rather you could swipe up or down to increase or decrease the electron orbits.

This was done simply using the SkiaSharp’s built in touch event handler, and calculating the touch movement direction, thus determining up or down direction! 😀

6. Atom Animated Uneven Orbits

 

So here’s the next progression step, with uneven orbits animation! I’m using a gradient oval drawing for each orbit, similar to what I’ve explained above in one of the previous steps. And I’m generating the Orbits Width upon a given random value.

You can take a look at the implementation: AtomAnimatedUnevnOrbitsPage.xaml.cs

7. ….T B C…..

This will be the next progression step. Since this post will be a continuously updated post along with every progression step I make in this fun project! 😀 So stay tuned!

 

 

That’s all for now!

So like I said at the beginning, this is a continuous fun protect, which I’ll keep on improving step by step. And once again, I will be accepting your pull requests for any improvements you suggest, or just drop a comment or message me of your suggestions. 😀

Don’t forget, feel free to try this project from my Github repo: github.com/UdaraAlwis/SkiaSharpAtomStructure 

I will be updating this post as the project progresses on hopefully! 😉

Let’s draw basic 2D Shapes with SkiaSharp…

So on my last post I shared a recap of my tech talk on SkiaSharp with Xamarin.Forms, check it out if you missed it: So I gave a Tech Talk on SkiaSharp with Xamarin.Forms…

There I talked about some of the most important parts of the whole 1 hour plus presentation-hands-on-labs session, in which I didn’t share all the details of the whole session. I did a pretty comprehensive demo session there, specially about the 2D drawing basics of SkiaSharp, which I didn’t highlight in that post.

Basic 2D Shapes with SkiaSharp…

So today I thought of sharing the demos I did there, about basic 2D shapes drawing with SkiaSharp more extensively… 🙂 Since there seem to be a lack of tutorials explaining this topic of, “draw basic Shapes with SkiaSharp”, which I think should be more important for beginners!

So buckle up fellas, let’s see how we could draw some of the most commonly used 2D shapes with SkiaSharp with ease… 😉

There’s many out of the box support for drawing basic 2D Shapes from SkiaSharp, such as DrawCircle(), DrawRectangle(), DrawLine(), DrawOval() and so on many more.  You could stright away use those methods or you could even go around it and use Paths and Lines drawing methods of SkiaSharp in order to draw them, which is completely up to you.

But SkiaSharp doesn’t have methods for drawing for every single kind of Geometrical shape there is out there. So if you want to draw some kind of complex shape, then you could basically use a combination of Paths and Lines drawing methods in SkiaSharp, which has many kinds of methods you could come up with. 😉 that’s the beauty of SkiaSharp! Anyways the choice of drawing methods are totally up to you!

Now if you want to get ahead of yourself, you may grab the live hands on demo code I did at the presentation which includes all of the below code, right from my github repo: https://github.com/UdaraAlwis/XFSkiaSharpDemo

Just on a note, here I will not be discussing basics of SkiaSharp or the setting up of SkiaSharp library or the Canvas properties and behaviours, I’ll directly get into the programming of the shapes drawing, but if you want to get a head start, head off to Xamarin SkiaSharp Documentation or my previous post, So I gave a Tech Talk on SkiaSharp with Xamarin.Forms…

1. Simple Stroke Line…

private void SkCanvasView_OnPaintSurface
		(object sender, SKPaintSurfaceEventArgs e)
{
	...
	
	// Drawing Stroke
	using (SKPaint skPaint = new SKPaint())
	{
		skPaint.Style = SKPaintStyle.Stroke;
		skPaint.IsAntialias = true;
		skPaint.Color = SKColors.Red;
		skPaint.StrokeWidth = 10;
		skPaint.StrokeCap = SKStrokeCap.Round;

		skCanvas.DrawLine(-50, -50, 50, 50, skPaint);
	}
}

 

We use the DrawLine() and pass in the Line’s starting point’s XY position and and ending point’s XY position, while passing in the paint configuration, SKPaint as we wish.

 

Since SkiaSharp support pure Xamarin.Forms you can straight away run all your native projects without any hassle of handling native code.

2. Drawing a Circle (Filled)

// Drawing a Circle
using (SKPaint skPaint = new SKPaint())
{
	skPaint.Style = SKPaintStyle.Fill;
	skPaint.IsAntialias = true;
	skPaint.Color = SKColors.Blue;
	skPaint.StrokeWidth = 10;

	skCanvas.DrawCircle(0, 0, 70, skPaint);
}

 

We shall be using the DrawCircle() whilst passing in the Circle’s center XY position and desired radius for it. To define whether its a Filled or Non-Filled circle we’ll be using Style property in our SKPaint configuration.

 

Next let’s draw a Circle with just the stroke (with filling the inner of the circle).

3. Drawing a Circle (Un-filled)

We do this by setting the Style property to Stroke! and everything else is the same 🙂

// Drawing a Circle Stroke
using (SKPaint skPaint = new SKPaint())
{
	skPaint.Style = SKPaintStyle.Stroke;
	skPaint.IsAntialias = true;
	skPaint.Color = SKColors.Red;
	skPaint.StrokeWidth = 10;

	skCanvas.DrawCircle(0, 0, 70, skPaint);
}

 

 

Look how simple eh 😉

4. A Square Rectangle!

How about a standard Rectangle? We shall use the SKRect object to configure our Rectangle as we wish and draw it up!

// Draw Rectangle
SKPaint skPaint = new SKPaint()
{
	Style = SKPaintStyle.Stroke,
	Color = SKColors.DeepPink,
	StrokeWidth = 10,
	IsAntialias = true,
};

SKRect skRectangle = new SKRect();
skRectangle.Size = new SKSize(100, 100);
skRectangle.Location = new SKPoint(-100f / 2, -100f / 2);

skCanvas.DrawRect(skRectangle, skPaint);

 

See it in action? 😉

 

The square root of 69 is 8 something, right? – Drake 😉 lol

5. Let’s draw an Ellipse…

There’s many ways to draw an Eclipse, but most common way is to use DrawOval(), as well as other kinds of complex drawings.

// Draw Ellipse
SKPaint skPaint = new SKPaint()
{
	Style = SKPaintStyle.Stroke,
	Color = SKColors.OrangeRed,
	StrokeWidth = 10,
	IsAntialias = true,
};

SKRect skRectangle = new SKRect();
skRectangle.Size = new SKSize(150, 100);
skRectangle.Location = new SKPoint(-100f / 2, -100f / 2);

skCanvas.DrawOval(skRectangle, skPaint);

 

 

So here we’re configuring a Rectangle with SKRect, which an Ellipse could be mathematically consist of.

6. How about an Arc shape?

Well it’s basically the same concept as of an Ellipse, but since we need an “Arc”, we’re going to use some basic mathematical angles to configure the starting angle, startAngle and sweep angle, sweepAngle of the Arc we’re going to draw with a Path object.

// Draw Arc
SKPaint skPaint = new SKPaint()
{
	Style = SKPaintStyle.Stroke,
	Color = SKColors.BlueViolet,
	StrokeWidth = 10,
	IsAntialias = true,
};

SKRect skRectangle = new SKRect();
skRectangle.Size = new SKSize(150, 150);
skRectangle.Location = new SKPoint(-150f / 2, -150f / 2);

float startAngle = -90;
float sweepAngle = 230; // (75 / 100) * 360

SKPath skPath = new SKPath();
skPath.AddArc(skRectangle, startAngle, sweepAngle);

skCanvas.DrawPath(skPath, skPaint);

 

So there we’re configuring our Path object to start off from -90 degrees and ends up at 230 degrees from the start point, drawing the Arc shape. Notice the comment I’ve added there, showcasing how you could also calculate the Arc’s drawing angle as a percentage value. 😀

 

Pretty cool eh! 😉

7. Did we forget Text?

Did you know you could even draw text on a SkiaSharp canvas right away by using DrawText() method.

// Drawing Text
using (SKPaint skPaint = new SKPaint())
{
	skPaint.Style = SKPaintStyle.Fill;
	skPaint.IsAntialias = true;
	skPaint.Color = SKColors.DarkSlateBlue;
	skPaint.TextAlign = SKTextAlign.Center;
	skPaint.TextSize = 20;

	skCanvas.DrawText("Hello World!", 0, 0, skPaint);
}

 

SkPaint object holds several properties for drawing Text on the canvas, such as TextAlright, TextSize and many more you could play around with..

 

Hello World, indeed! 😉

8. Let’ draw a simple Triangle?

Well SkiaSharp doesn’t have a out of the box method call for drawing a Triangle, this is where simple Drawing path and points comes into play.

So basically what we do is, we’ll draw three lines that’s interconnects at the ending points, using DrawPoints() method and pass in the list of Points that’ll draw the Lines…

// Draw Rectangle
SKPaint skPaint = new SKPaint()
{
	Style = SKPaintStyle.Stroke,
	Color = SKColors.DeepSkyBlue,
	StrokeWidth = 10,
	IsAntialias = true,
	StrokeCap = SKStrokeCap.Round
};

SKPoint[] skPointsList = new SKPoint[]
{
	// Path 1
	new SKPoint(+50,0),
	new SKPoint(0,-70),

	// path 2
	new SKPoint(0,-70),
	new SKPoint(-50,0),

	// path 3
	new SKPoint(-50,0),
	new SKPoint(+50,0),
};

skCanvas.DrawPoints(SKPointMode.Lines, skPointsList, skPaint);

 

See it first may be?

 

So now if you think about it, you could actually draw any kind of a Shape with interconnecting Points and Paths using the above method. 😀

9. Draw any Shape?

It’s true earlier step, in Triangle drawing I said you could use the DrawPoints() and a bunch of Points to draw any kind of shape in SkiaSharp. This is actually a painful, but there’s actually a better way… 😉 yaay!

So basically if you needed to draw any kind of shape, all you need is a Path and a bunch of Points that interconnects. A much easier way to do this is by using a SKPath configuration object, using this you could pass define the Starting Point of the drawing path, move around the drawing path with interconnecting Points by using MoveTo() and LineTo() calls. For this you use the mighty DrawPath() method, which you could use to draw anything on the canvas. 😀

// Draw any kind of Shape
SKPaint strokePaint = new SKPaint
{
	Style = SKPaintStyle.Stroke,
	Color = SKColors.Black,
	StrokeWidth = 10,
	IsAntialias = true,
};

// Create the path
SKPath path = new SKPath();

// Define the drawing path points
path.MoveTo(+50, 0); // start point
path.LineTo(+50, -50); // first move to this point
path.LineTo(-30, -80); // move to this point
path.LineTo(-70, 0); // then move to this point
path.LineTo(-10, +90); // then move to this point
path.LineTo(+50, 0); // end point

path.Close(); // make sure path is closed
// draw the path with paint object
skCanvas.DrawPath(path, strokePaint);

 

There you go…

 

So with the use of SKPath, you could draw any kind of 2D shape as you wish… 😀

10. Final shape?

Oh sorry! there ain’t none! 😛 just put up a 10th point for the fun of it! 😉

Well you could grab all of the above code up in my Github repo: https://github.com/UdaraAlwis/XFSkiaSharpDemo That right there is actually the live hands on demo code I did at my original presentation…

So now get out of here and start drawing 2D with SkiaSharp! 😀

or may be check out my talk on SkiaSharp…

Shape the love fellas! 😀

-Udara Alwis.

So I gave a Tech Talk on SkiaSharp with Xamarin.Forms…

A little back story…

Few months back our company was asked to do a graphics application, so we decided to take a look into graphics rendering libraries available for Xamarin.Forms, given the limited time, we thought of going for SkiaSharp over other alternatives, which we had very little knowledge of how to work with.

But to our surprise we managed to build an incredible app with beautiful interactive graphics and animations completely using SkiaSharp with Xamarin.Forms. So I thought of sharing my experience with the fellow dev community. 😀

Opportunity…

So few weeks back (18th June, 2017), I had the opportunity to give a tech talk-hands on demos, at Singapore Mobile .Net Developers  meetup, under the topic “2D Graphics Rendering in Xamarin.Forms with SkiaSharp”!

udara alwis presentation skiasharp xamarin microsoft

So I’m about to share some of the stuff I presented at this meetup, although I will not be diving into every single detail I talked about there, only be focusing on the key points (mostly on the hands on demo bits). If you’re interested in learning SkiaSharp for Xamarin.Forms, go ahead to the the incredible documentation provided by Xamarin: https://developer.xamarin.com/skiasharp/

Here’s the short recap of the presentation I did over there! 😉

2D Graphics Rendering in Xamarin.Forms with SkiaSharp!

So let’s get started off with the Slideshow Presentation…

And you may grab the live hands on demo code I did at the presentation from my github repo: https://github.com/UdaraAlwis/XFSkiaSharpDemo

Now let’s recap…

Behold the incredible 2D Rendering Engine for Xamarin and Xamarin.Forms, SkiaSharp!

An open source project originally developed by Google(Thank you <3), from C++ language, by the name Skia. It is used across a huge variety of Google’s products, including web graphics rendering and so on. This is a Immediate mode 2D vector graphics rendering system, this framework allows you to do 2D graphics, handling and manipulating image resources and text and a lot of cool stuff. 😀

So SkiaSharp is the C# and DotNet wrapper of Skia framework allowing us to use it right on top of Xamarin, a mono based open source project, where you could add your own contribution to it via: github.com/mono/SkiaSharp!

SkiaSharp for Xamarin.Forms comes with the SKCanvasView that inherits from Xamarin.Forms.View which allows you to use it as just another View in your PCL code, and you don’t have to handle any native implementation, everything is accomplished right in your PCL code. 😉

SkiaSharp basics Demo..

For setting up SkiaSharp, open your nuget manager and install “SkiaSharp.Views.Forms” across your Xamarin.Forms solution, including PCL and platform specific projects.

Add the SKCanvasView to your page as you wish.

<ContentPage
    x:Class="XFSkiaSharpDemo.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:forms="clr-namespace:SkiaSharp.Views.Forms;assembly=SkiaSharp.Views.Forms"
    xmlns:local="clr-namespace:XFSkiaSharpDemo">

    <forms:SKCanvasView x:Name="SkCanvasView" PaintSurface="SkCanvasView_OnPaintSurface" />

</ContentPage>

 

Notice the PaintSurface event, the most important execution point you need to handle in order to render your graphics on the SKCanvas. Every time you need to do any kind of a drawing or rendering of 2D graphics on your Canvas, you need to do it in this event, this method is first invoked when the Page appears on the screen, and then if the orientation changes or you could even manually invoke it by calling InvalidateSurface() of your SkCanvasView.

Let’s do that…

public partial class
	MainPage : ContentPage
{
	...

	private void SkCanvasView_OnPaintSurface
		(object sender, SKPaintSurfaceEventArgs e)
	{
		// Init skcanvas
		SKImageInfo skImageInfo = e.Info;
		SKSurface skSurface = e.Surface;
		SKCanvas skCanvas = skSurface.Canvas;

		// clear the canvas surface
		skCanvas.Clear(SKColors.SkyBlue);

		// retrieve the canvas info
		var skCanvasWidth = skImageInfo.Width;
		var skCanvasheight = skImageInfo.Height;
	}
}

 

This event provides you with all the required properties and values to execute your 2D rendering, such as the SKCanvas instance, which is the actual canvas you’re going to do the 2D drawing on, SKImageInfo instance which provides you with details such as actual Width and Height by pixels and so on.

The Clear() method call, clears up the canvas surface and prepare it for rendering new content, by passing it a SKColor object, you can paint it with that color.

2D Graphics with SkiaSharp..

The SKCanvasView is actually a placeholder for the SKCanvas which you can access in the PainSurface() event.

There’s many ways to draw or render stuff on our Canvas, but SkiaSharp also provides us predefined methods that allows us to draw simple types of shapes such as Circles, Lines and Texts, etc.

So usually when you are to do some complex drawings you would be using a combination of all those drawing methods at a given rendering cycle.

Transform Operations…

SkiaSharp allows you to do all kinds of Translations, Scaling, Rotating and even Skewing on the Canvas.

Usually on the Canvas, the X,Y coordinate system starts from the top left most corner and Y axis increments vertically and X axis increments horizontally.

So lets see how we could manipulate this in our favor and do some basic Translation and Scaling on the Canvas.

private void SkCanvasView_OnPaintSurface
	(object sender, SKPaintSurfaceEventArgs e)
{
	...
	
	// move canvas's X,Y to center of screen
	skCanvas.Translate((float)skCanvasWidth / 2,
				(float)skCanvasheight / 2);

	// set the pixel scale of the canvas
	skCanvas.Scale(skCanvasWidth / 200f);
}

 

There we are Translating the Canvas’s X,Y coordinate system to be started off of the center of the screen, and then Scaling the Canvas to the ratio of 200 pixels according to the actual canvas Width.

SKPaint object..

SKPaint object is one of the most important element in SkiaSharp, it holds the configuration for any given type of 2D rendering, so you’ll be storing your drawing configuration in that object, such as Color, Style, Stroke Width/Height, Anti Alias and so on.

SKPaint skPaint = new SKPaint()
{
	Style = SKPaintStyle.Fill,
	IsAntialias = true,
	Color = SKColors.Blue,
};

 

There’s how you instantiate a SKPaint object which you’ll using to render your 2D graphics, it’s got all kinds of drawing properties and configurations you can play around with. 🙂

Draw a simple Circle (Filled and Non-Filled)

Let’s get our hands dirty with some actual 2D drawing eh! 😉

// Drawing a Circle
using (SKPaint skPaint = new SKPaint())
{
	skPaint.Style = SKPaintStyle.Fill;
	skPaint.IsAntialias = true;
	skPaint.Color = SKColors.Blue;
	skPaint.StrokeWidth = 10;

	skCanvas.DrawCircle(0, 0, 50, skPaint);
}

...

// Drawing a Circle Stroke
using (SKPaint skPaint = new SKPaint())
{
	skPaint.Style = SKPaintStyle.Stroke;
	skPaint.IsAntialias = true;
	skPaint.Color = SKColors.Red;
	skPaint.StrokeWidth = 10;

	skCanvas.DrawCircle(0, 0, 70, skPaint);
}	

 

We shall be using the DrawCircle() whilst passing in the Circle’s center XY position and desired radius for it. To define whether its a Filled or Non-Filled circle we’ll be using Style property in our SKPaint configuration.

 

Look how simple and beautiful eh 😉

Since SkiaSharp support pure Xamarin.Forms you can straight away run all your native projects without any hassle of handling native code.

To learn more about drawing on the Canvas you can check out the official Documentation: https://developer.xamarin.com/guides/cross-platform/drawing/

Handling User Interactions…

When it comes to most Xamarin.Forms components, they do not have touch handlers, however the SKCanvasView comes default with a Touch event handler, Touch and a boolean property to enable or disable Touch Events, EnableTouchEvents.

You can straightaway use that even and property to handle touch events on the SKCanvas.

<forms:SKCanvasView x:Name="SkCanvasView" 
		EnableTouchEvents="True" 
		Touch="SkCanvasView_Touch"
		PaintSurface="SkCanvasView_OnPaintSurface" />

 

You can subscribe to it and look for the type of touch event and handle it.

private void SkCanvasView_Touch(
object sender, SKTouchEventArgs e)
{
	if (e.ActionType == 
		SkiaSharp.Views.Forms.SKTouchAction.Pressed)
	{
		_lastTouchPoint = e.Location;
		e.Handled = true;
	}

	_lastTouchPoint = e.Location;

	// update the Canvas as you wish
	SkCanvasView.InvalidateSurface();
}

 

As you can see it gives you the Touch point location. You can get a hold of the event and the touch point and you want to do some drawing on the SKCanvasView, then you could call the InvalidateSurface().

private SKPoint _lastTouchPoint = new SKPoint();
private void SkCanvasView_OnPaintSurface
(object sender, SKPaintSurfaceEventArgs e)
{
	...
	
	using (SKPaint paintTouchPoint = new SKPaint())
	{
		paintTouchPoint.Style = SKPaintStyle.Fill;
		paintTouchPoint.Color = SKColors.Red;
		skCanvas.DrawCircle(
			_lastTouchPoint.X,
			_lastTouchPoint.Y,
			50, paintTouchPoint); // 45
	}
}

 

Here it is in action… pretty simple eh! 😉

  

But this touch handler is very primitive, as in if you want to handle multiple concurrent touch points, or special gesture touches, pan, or zoom and so on, then you need to implement a more advanced low level touch handler, something described as here:

https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/effects/touch-tracking/

That way you could simply attach the above TouchEffect just as a normal effect and see the complex touch events in action.

<Grid>
	<skia:SKCanvasView x:Name="SkCanvasView"
		PaintSurface="SkCanvasView_OnPaintSurface" />
		
	<Grid.Effects>
		<tt:TouchEffect Capture="True"
			TouchAction="OnTouchEffectAction" />
	</Grid.Effects>
</Grid>

 

There you go! 😀

Bitmap Image Handling….

Images are pretty crucial when it comes to  2D Graphics, it gives more of added advantage over your design idea.

As of Xamarin.Forms, the conventional the conventional way of loading an image is, either as an Embedded Resource or Platform Specific Resource.

So in SkiaSharp for Xamarin.Forms, provides you SKBitmap or SKImage for handling your image resources. You have few options to load an image, from a data stream, file path and so on.

The most common way in the sense of Xamarin.Forms architecture, you have the option of loading your Images directly from PCL as Embedded Resources, and then convert it to a SKBitmap or SKImage.

string resourceID = "XFSkiaSharpDemo.Resources.xamarinmonkey.png";
Assembly assembly = GetType().GetTypeInfo().Assembly;

SKBitmap skBitmap;

using (Stream stream 
		= assembly.GetManifestResourceStream(resourceID))
using (SKManagedStream skStream
		= new SKManagedStream(stream))
{
	skBitmap = SKBitmap.Decode(skStream);
}

skCanvas.DrawBitmap(skBitmap, 
	SKRect.Create(-50, -50, 100, 100), null);

 

There you have it, we are using the DrawBitmap() method for drawing the image on canvas.

 

But if you have a Xamarin.Forms ImageSource at hand and you need to use in SKCanvas, then you have convert it a Stream object and convert it to SKBitmap, which you could use to manipulate or draw using SkiaSharp on the Canvas. 😉

Image Filters..

Thanks to SkiaSharp you don’t have to manually implement image filters at all, since it packs a pretty cool set of Image Filters out of the box. 😀

Here’s a small sample of a blur image filter implementation…

// built-it blur image Filter
var filter = SKImageFilter.CreateBlur(5, 5);
var skPaint = new SKPaint();
skPaint.ImageFilter = filter;

skCanvas.DrawBitmap(skBitmap, 
	SKRect.Create(-50, -50, 100, 100), null);

 

SKImageFilters is the class that provides the built in filters. 🙂 You attach that object to a SKPaint configuration and draw the Bitmap with it!

 

Keep in mind, there’s a lot more default Image Filters you could play around with! 😉

*drum beat*! 😀

Rendering Animations…

Although Xamarin.Forms packs some pretty decent set of Animations out of the box, we don’t much control over the animation for customization.

But using something like a 2D Rendering Engine, we could create whatever the animation or customization as we wish. SkiaSharp of course is a great option, but that being said, there’s no direct Animation handling available. Because it’s simply a 2D vector rendering engine.

So this means if you want to render some continuous animation with SkiaSharp, you need to handle every single frame of it manually from your code.

So by actual implementation there’s few ways to do this, but the actual underlying idea is to repeatedly render a given set of values on the Canvas, preferably triggered by a continuous timer of sorts.

Stopwatch stopwatch = new Stopwatch();
bool pageIsActive;
float t;
const double cycleTime = 1000; // in milliseconds

private void InitAnimation()
{
	pageIsActive = true;
	stopwatch.Start();

	Device.StartTimer(TimeSpan.FromMilliseconds(33), () =>
	{
		// calculate t for current 
		// tick with regards to cycletime
		t = (float)(stopwatch.Elapsed.TotalMilliseconds
					% cycleTime / cycleTime);
		// invoke redraw on canvas
		SkCanvasView.InvalidateSurface();

		if (!pageIsActive)
		{
			stopwatch.Stop();
		}
		return pageIsActive;
	});
}

 

The above shows you you could create a simple continuous pulse generator relative to milliseconds and execute a continuous animation. In simple terms the Timer is running each 33 milliseconds, calculates a value (t) based on the total elapsed milliseconds on the stopwatch, relative to the cycle time (controls the speed of animation) and repeats. Then calls the SKCanvas redraw. Make sure to call this method on PageAppearing() to start the timer and set the pageIsActive = false on PageDisappearing() to the timer stops.

private void SkCanvasView_OnPaintSurface
	(object sender, SKPaintSurfaceEventArgs e)
{
	... 
	
	// calculate circle radius for this cycle
	float radius = 70 * t;

	// Drawing a Circle Stroke
	using (SKPaint skPaint = new SKPaint())
	{
		skPaint.Style = SKPaintStyle.Stroke;
		skPaint.IsAntialias = true;
		skPaint.Color = SKColors.Red;
		skPaint.StrokeWidth = 10;

		skCanvas.DrawCircle(0, 0, radius, skPaint);
	}
}

 

There as you can see we are drawing the Circle at the given rendering cycle with relative to the generate “t” value at the Timer. So the Circle’s radius will keep on varying from 0 – 70, thus creating the animation effect.

 

Now keep in mind there’s nothing to worry about the rendering performance, since SkaiSharp is a rendering engine. 🙂 You can configure the animation even more faster as you wish, it wouldn’t make much effect on app’s performance! 😉

More Awesome Stuff…

If you want to learn more, check out Xamarin official documentation: https://developer.xamarin.com/guides/skiasharp/

If you need to check out sample code and demos : https://developer.xamarin.com/SkiaSharpFormsDemos/

This presentation’s demo on github…

That’s right, you can get the full demo code I’ve showcased in the presentation up in my github: https://github.com/UdaraAlwis/XFSkiaSharpDemo

I haven’t shared all the demo code I’ve presented in this blog post, but you call find all of the demo code from my git repo above! 🙂

Conclusion…

Yep that’s pretty much it, just get out of here and build something awesome with SkiaSharp! 😉

Share the love! 😀

Cheers!
– Udara Alwis

Yaay! I became a Xamarin Certified Mobile Developer! :D

So finally on 9th of June 2017, I became a Xamarin Certified Mobile Developer. So here’s my experience of the whole Xamarin University, Certification Exam, and some tips and tricks that might help you! 🙂

Well I’ve been using Xamarin Platform for over 2 and half years now, but I never really thought of getting the official Xamarin Certification until recently my boss encouraged me to and financially supported it.

Down the memory lane of my Mobile Development enthusiasm…

So here’s a little sharing of memories down the memory lane and some tips for getting the Xamarin Certification.

I first started off developing mobile apps on Android platform, given my love for Java programming back in the early days. So I self learned Android App Development back in the middle of 1st year of my college using online tutorials and documentation.

Then at the end of 1st year, I was introduced to Windows Phone App development, which I got completely hooked on it, and then Windows Store App Development and so on, where I ended up publishing over 20+ apps to the Microsoft App Store during the next few years.

Next lucky enough I got a mobile developer opportunity at a medium size local company where it was for Xamarin Mobile Development back in 2014 December. 😀

Learning the whole Xamarin Platform by myself, I ended up completing a full fledged mobile app for that project in that company using Xamarin Forms.

Finally in 2015 December, got an overseas opportunity in Singapore for a Xamarin Mobile Developer position, which is where I ended up mastering the Xamarin Platform, Xamarin Android/iOS native development, hacking to push boundaries of the platform and so on and finally living my dream of being a Mobile App Developer. 😀

And that is where I’m currently working at June 2017, enjoying everyday of it while diving in the goodness of Xamarin Mobile Development. 😉


Xamarin University Training and Certification Preparation…

I was lucky enough my company sponsored me for Xamarin University Subscription. Otherwise its about 1000 USD for 1 year subscription or there a new monthly subscription plan with a very reasonable pricing.

Once you have the subscription you get full access for all the incredible learning materials and live lecture sessions in Xamarin University.

Is it worth it?

Now although at this point I already had like 2 years of Xamarin Mobile developement experience, I must admit that I learned way more and strengthened my knowledge on Xamarin top to bottom thanks to Xamarin University. So if you ask me if it’s worth it? at least for the Knowledge? DEFINITELY YES!

Mandatory Sessions

There’s a mandatory list of sessions that you have to complete before taking the exam, you could completely them either by attending the live lecture sessions or taking self-learn sessions (if available). Yes, some of those mandatory sessions doesn’t have the ‘self-learn’ option yet, so you have to attend to a live lecture session and get your attendance marked for it. 🙂

Instructors?

Mark my words, the instructors in Xamarin University are top-notch, and industry experts with a lot of knowledge and experience, there’s no doubt about them. You can ask anything from them regarding the session, even while the session is going on, they are very helpful and friendly, not to mention their great teaching skills. 🙂

Memorizing vs Understanding!

Do not MEMORIZE! just UNDERSTAND the content! The sessions are structured in a way that it helps you to actually understand the content with step by step exercises. I’ve never taken a single note on any of the sessions, nor tried to memorize stuff(although I’m not very good at it either), just followed through sessions and focused well during them. That’s all it takes!

Anything else?

You can take any live lecture session as many times as you wish, until you feel comfortable with the topic. There’s also many extra sessions you could attend to improve your knowledge in Azure, UI Test, Xamarin Android, Xamarin iOS. It’s good to keep in mind that the exam mandatory sessions are mainly about Xamarin Forms cross platform related topics, so you don’t have to worry if you don’t have much in-depth knowledge about native mobile development. 🙂

They also provide you a Study-Guide check-list to go through to make sure you’re prepared for what’s actually required: https://university.xamarin.com/content/certification#study-guide

Once you’ve completed the mandatory sessions, then you become eligible to sit for the certification exam!


Certification Examination!

So the Certificate Exam is a 3 hours, MCQ exam (Multiple Choice Question) which has 150 questions, and you should score over 80% in order to pass the exam.

The questions scope…

The questions are going to be completely based on the mandatory sessions in Xamarin University. Heavily focused on the Xamarin.Forms cross platform related topics. Personally I did not get any questions that are out of the scope.

So how were the questions…

If you’ve got a solid knowledge on the mandatory sessions, then you have nothing to worry about. Not keep this in mind, about 40% of the questions are straight and easy, but the rest are not going to be hard, but tricky, meaning it’s going to be little bit twisted, so you need to pay good attention to the details in each question before you pick the answer. 😉

Understand the content in the sessions, not memorize!

Basically you won’t be able to make it through the exam if you’re just trying to ‘memorize’ everything in your head, you need to have a ‘good understanding’ of the session content, in order to answer the tricky 60% of the questions.

After the exam?

Once you finish the exam, you get the results immediately. 😉 Then its time to PARRTTAAYYY!!! 😀

Xamarin University and Certification benefits!

First of all the incredible amount of knowledge and experience you gain in the whole process of Xamairn University and the Certification is priceless.

Not to mention the global recognition as Xamarin Certified Mobile Developer, having the official certificate directly validates you as someone who actually knows your way around Xamarin-stuff. Although it does not prove you as an ‘expert’, which is totally dependent on your personal industry experience.

Access to Xamarin DevConnect portal, to showcase your portfolio and connect with fellow developers.

There are few other awesome benefits you get according to Xamarin official site as follows. Certification is valid for 1 year from the date you have passed the exam. Certifications can be verified on our public Xamarin Certified Developers page.

Receive a badge, fun Xamarin swag, and an invitation to join the official Xamarin Certified Developers community on LinkedIn.

Cool, so what do I get to show off?

Except for the massive amount of knowledge and experience I gained from the Xamarin University Sessions and Training, here are some other show-off stuff I got after being certified.

So brace yourselves for some self promotional bragging! 😛

Xamarin Certified Developer Verification Online:

https://university.xamarin.com/certification?q=Udara@xamariners.com#verify

You get a link that can be shared online for the verification of your Certification status. This is the source you could include in your LinkedIn or personal portfolio for the verification.

Xamarin University Profile Badge: 

Once you get the certification, your Xamarin University profile gets updated as such.

Xamarin Certified Developer Certification (soft copy): 

You actually get a PDF version of your certification (here is a screenshot of it).

Bunch of Xamarin Certified Developer badge Images (HD):

Then you get a whole bunch of Certified Mobile Developer badges in low, mid and high resolution for you to share on any of your websites or portfolios. 🙂

Xamarin DevConnect Profile:

You get access to Xamarin DevConnect, the official Xamarin Certified Developer portal from Xamarin, where you can publish your portfolio, connect with fellow certified developers from all over the world, and open up yourself for new opportunities.

https://devconnect.xamarin.com/profile/389


Well that’s it all I got for now… 😀

Although some claim that you get kind of a Xamarin souvenir trophy and a goodie bag by mail, but I’m yet to get any of that. lol. *fingers cross* 😛

So If anyone needs any help or clarifications regarding Xamarin Certification, I’m more than happy to help, drop me a mail or comment down in the post. 🙂

To get started:  https://www.xamarin.com/university

Good luck everyone with your Xamarin Certification! 🙂

Cheers!

I am a Developer and I Code with ‪#‎VisualStudio‬ ! ;)

I code with Visual Studio 2

I am a Developer and I Code with #VisualStudio. 😀 Build your own Visual Studio profile today at aka.ms/myVisualStudio!
Yep that’s me, that hyper-active kid in the photo lol 😛
Kudos to whoever created this simply awesome tool. 😀
– Udara Alwis
[ÇøŋfuzëРSøurcëÇødë]

So I gave a Tech Talk at Dot Net Developers Meetup, Singapore hosted by Microsoft…

Yeei! 😀 I got an awesome opportunity present a tech talk at Dot Net Developers Meetup in Singapore which was hosted by Microsoft. This happened to be my first ever Presentation on Xamarin, and yeah it was totally awesome. A great enthusiastic crowd and everything went pretty well.. 🙂

Thank you so much for the Organizers and Microsoft for this incredible opportunity, and I’m truly humbled by it.

There I spoke about Xamarin and Xamarin Forms, Xamarin UI Rendering process, Overriding this process through Custom Renderers, and important facts to keep in mind when implementing Custom Renderers in Xamarin Forms.

So I thought of putting out a small article on the Summary of this tech talk on my blog. 😀

Xamarin Forms Custom Renderers for the Rescue…

Here’s the slideshow I used during this talk…

Xamarin is…

Xamarin is truly a great platform. It let’s you create mobile applications using C# dot net having full Native Performance as well as Looks and Feels of each Native Platform.

Xamarin Forms Custom Renderers for the Rescue.004

As you can see in the diagram, thanks to Xamarin now we can maintain the same code base across all three mobile platforms, having the individual native UI implementation, which allows us to maintain up to about 70% percent shared codebase. So yeah its all Great.

Xamarin Forms is…

Xamarin Forms, in one single word, is awesome! Its more like the cross platform extension of Xamarin this is the component which brings to life of the concept, Write once, Run Everywhere, and not Suck allowing us to share the UI code layer among three platforms. So you no longer need to implement the UI separately for each platform.

Xamarin Forms Custom Renderers for the Rescue.005

Xamarin and Xamarin Forms ?

Some people are confused about these differentiation between Xamarin and Xamarin Forms, let me put it this way…

Xamarin Forms Custom Renderers for the Rescue.006

Xamarin Forms is more like the true cross platform extention of Xamarin. Where as Xamarin Forms provides us a unified UI Layer which has all the common UI controls (Layouts, Labels, TextBoxes, Buttons, etc…) of all three mobile platforms, with almost every single common property of those controls.

Still Confused ? Let me explain…

Xamarin Forms Custom Renderers for the Rescue.007

In your left hand side you can see the Native Xamarin architecture where you share the back-end code base, but you have to implement the UI separately for each platoform, allowing us to share upto 70-80% of code base.

Where as in Xamarin Forms you can share almost upto 100% of the code base across all three platforms with the Shared UI Layer.

A little Story about a fresh Xamarin Forms developer…

There’s this developer who started developing an application with Xamarin forms, where he’s given all the UI sketches and so on.

Xamarin Forms Custom Renderers for the Rescue.008

So he start off with default nice and simple controls in Xamarin Forms and manages to implement the basic UI design of the app. Then he slowly gets into complex UI designs implementations…

So he starts going through all the available properties in these Xamarin Forms Controls, and begins to wonder where are all the properties that he needs to be using in order to customize the app accordingly to the complex design.

So he looks up and down, here and there, wondering where did all the properties go?

Oh boy, he’s in trouble, isn’t he… He realise Xamarin Forms UI controls has limited set of properties for customization, and its very hard to do complex customization in these controls.

Any Solutions ?

Any solutions ? Well he could always go back to native development, but its late for it now, and it’ll put him through a lot of trouble for sure, having to implement in three platforms.

Now that’s where Xamarin Forms Custom Renderers comes in for the rescue, let me explain.

Xamarin Forms Custom Renderers for the Rescue.010

Xamarin Forms UI Rendering process…

Each and every UI Control in Xamarin Forms has it’s own Native Renderer which renders and maps its Properties and Behaviours to the Native Control level.

So yeah behold the Magic of Xamarin Forms, this happens accordingly to the Native Platforms. This is why we get the Native look and feel and performance with Xamarin Forms.

Xamarin Forms Custom Renderers for the Rescue.011

Take a look at the Diagram here it shows how the default texbox UI Control of Xamarin Forms, which is called “Entry” control gets rendered down to the Native level through the Renderers. Now focus down through the iOS rendering, where the Entry control gets rendered down to the native UITextField control. And on Android and Windows Phone, EditText and UserControl respectively.

Overriding this Rendering Process ?

Xamarin has allowed us to access this Rendering process, which in return allows us to Override this default process and use it for our own requirements.

Xamarin Forms Custom Renderers for the Rescue.012

So by accessing this process we can customize all kinds of properties and behaviours of the Xamarin Forms controls, in each platform according to our needs.

Xamarin Forms Custom Renderers…

So in order to access this rendering process we need to create Custom Renderers of our own by sub classing the base Renderers Xamarin provides. Thereby it allows us to access and modify the native level properties and behaviours of the Xamarin Forms Controls.

Xamarin Forms Custom Renderers for the Rescue.013

Take a look at the Diagram above, that’s how Custom Renderers gets involved in the Rendering process, where as the Xamarin Forms Entry control goes through the Custom Renderer and down to the base renderer, where we control and modify its properties and behaviours in our Custom Renderer as we need.

How to create Xamarin Forms Custom Renderers ?

Just 3 simple steps…

  1. First you create a Custom Control by subclassing the default Xamarin Forms Control that you need to create a Custom Renderer for.
  2. Second you consume that subclassed Custom Control in your Xamarin Forms application.
  3. Thirdly and finally, you implement the Custom Renderer in the Native levels project.

Yeah how hard could it be, just three simple steps! 😉

Here’s a Simple Custom Renderer Demo on the house…

Check out the live demo Custom Renderer I implemented during this presentation on my Github from below, https://github.com/UdaraAlwis/XFCircleCornersButtonControlDemo

Important facts to consider WHEN implementing Custom Renderers…

So here are some important facts to keep in mind when you implement Custom Renderers in Xamarin Forms, so that you get a good understanding about how to implement a custom renderer and what to keep in mind…

1. Always Export your Custom Renderers…

Whenever you create a custom renderer you need to Export it and register it, otherwise Xamarin would not recognise your Custom Renderer and it will go ahead with the default base class Renderer for your Custom Control.

Capture

2. Overriding the OnElementChanged Method…

Whenever a Custom Renderer is being execute, the first method it fires is the OnElementChanged() method.

This method gets called when the Rendering process starts for the custom control, which allows us the opportunity to to tap into the native properties and behaviours and modify them as we wish by overriding this method.

Also something to keep in mind this method consumes an important parameter, ElementChangedEventArgs which contains two important Properties.

  1. The OldElement property represents the Xamarin Forms level Control this renderer was attached to (previously attached to) and
  2. The NewElement property represents the Xamarin Forms level Control this renderer is currently attached to, its more of a reference.

So if you are using any Event Handlers in your Custom Renderer, you have to keep an eye out for these two properties in order to Subscribe and Unsubscribe accordingly to prevent memory leaks.

Capture1

3. Control vs Element Property…

If you think about it, Custom Renderer is more like a middle guy, in between Xamarin Forms level Control and the Native level Control, where as it’s got hooks for both levels.

So those hooks are represented by these two important properties, Control and Element.

Element property, it holds a reference to the Xamarin.Forms control that’s being rendered, so you could use this property to access anything on the Xamarin Forms level of the custom control, such as Text, WidthRequest, HeightRequest and so on.

Control property holds a reference to the Native Control being used of the Custom Control. So using this property you can straight away add your native customisations and behaviours to the Rendering Control.

3. Overriding the whole Native Control ?

What if you want to get rid of the default Native Control associated with your Custom Renderer ? Create your own Native Control and use it for your Custom Control ?

As an example You need to have a TextBox with an underneath shadow, in iOS you can’t do this with the default native UITextView, so one way to do it is by adding another UIView along with the UITextView, where as you merge two native views together to form one View.

So for instances like that, you could use the SetNativeControl() method, and pass in your custom native view, which will get rid of the default native view and override it with your custom native view.

But you have to keep in mind something very important, hence you are flushing away the default native control, you have to handle all the Behaviours (Events) of your own Native Control manually by yourself and map it back and forth with the Xamarin Forms level.

4. Creating your own Base Renderer…

For every Xamarin Forms Control, there is a Base Renderer, that maps it to the Native Level and we use those Base Renderers all the time such as Button Renderer, Label Renderer and so on.

Now what if you wanted to create your own Base Renderer ? Let’s say you are creating a total complex Custom Control by yourself, and you need to have your own Renderer for it?

YES! it is possible, you just simply have to derive your Base Renderer from the generic ViewRenderer<?,?> where as you have to pass in your Custom Renderer type name and the associating Native Control type name for the renderer.

Well actually Xamarin doesn’t really recommend this, there some instance that you need to move towards this approach.

Let me Share some Wisdom…

Xamarin Forms Custom Renderers for the Rescue.022

Here’s something interesting I really want share with your all is that, Xamarin doesn’t really require in depth Mobile Development knowledge but it is very beneficial to have some, specially in scenarios like these Custom Renderer implementation. The more you are aware of the Native development, the more advantages for you.

So if you are planning to move towards Xamarin mobile development, I would suggest you take a little look at native development as well… Which will prepare you better for your Xamarin Mobile Development journey.

Important facts to consider BEFORE implementing Custom Renderers…

Earlier I mentioned about the facts that you need to keep in mind when you implement Custom Renderers, now let’s see what are the facts you need to focus BEFORE you decide to implement Custom Renderers in your application.

 

1. Think twice…

You need to think twice before you move on towards Custom Renderer implementation for your Application. Once you get familiar with Custom Renderer implementation, you get very tempted to go for custom renderers all the time even for the simplest requirement, but trust me it is not a good practice at all.

Why I say this is because, and untold truth about Custom Renderers is that, they are a little process intensive.

Therefore it’s wise to first of all explore all the possible solutions you could come up with from Xamarin Forms level it self to solve your requirement. So do not over-use Custom Renderers just because of the ease of development.

You could also try out other alternatives such as,

  1. Xamarin Forms Controls sub-classing and forming Custom Control (by merging multiple Controls to create a new Control).
  2. Xamarin Forms Effects (which is almost like Custom Renderers but simplified).

 

2. Re-usability…

Whenever you decide to implement a Custom Renderer You need to pay attention to the reusability of it. Make sure to implement it in a way its reusable as much as possible.

When ever you implement Custom Renderers, don’t only focus on the current implementation, think ahead and implement all the possible needs in one go, without implementing custom renderers for every single need from one type of control.

Since Custom renderers are process intensive it very important to focus on reusability.

3. Mapping of Xamarin Forms -> Native Level…

Last but not least before you implement your Custom Renderer always make sure to take a look down through your Rendering Hierarchy…

Xamarin Forms Custom Renderers for the Rescue.026

Look at the available Properties and Behaviours down to the Native control and see whether it actually fulfils your requirements, in all three platforms (Android, iOS, Windows Phone). That way you will have a better idea on how to implement the Custom renderer more efficiently.

Conclusion…

Xamarin Forms Custom Renderers for the Rescue.028

Custom Renderers plays an extremely important role in Xamarin Forms development. In my opinion it’s more like the Magic behind the whole Xamarin Forms Awesomeness.

Don’t be scared of Custom Renderer’s because they are here for your rescue.

Also finally make sure to keep in mind all the important tid bits I discussed today, so it will help you implement custom renderers more efficiently and effectively. 🙂

AAAANND THAT BROUGHT US TO THE END OF THE PRESENTATION! Hope this was helpful for anyone missed this session and keep in touch everyone! 😀

Once again Thanks for the Organisers for organising this event and Microsoft for hosting. As well as the enthusiastic crowd. 🙂

– Udara Alwis
CODENAME: [ÇøŋfuzëРSøurcëÇødë]

https://www.linkedin.com/in/udaraalwis

https://www.facebook.com/confuzed.sourcecode

Few words about the ÇøŋfuzëÐ SøurcëÇødë Blogging Style ! ;)

Yes I am a Developer! A Software Engineer by career!

But truth be told, I’m not the typical type of software-engineer-developer-geek ! 😛

I’m a hyper-active, overjoyed, crazy enthusiastic, energized, optimistic human being! 😉

I often go on Adventures, Hiking, Running, Cycling and Basketball, also includes Socializing and talking to People in Public…

I run a lot ! literally like a mad man, and I’m addicted to it. It makes me feel free, refreshed, de-stressed, energized, hyped up, and allows me to push myself beyond the physical limitations. Hence it keeps reminding me that nothing is impossible as long as I keep on pushing myself without giving up.

I enjoy every single moment of my life, seeing the positive perspective of everything that happens around me. And I never regret any decisions I have ever made. I like making others happy and cheering up people around me is something I enjoy a lot. 😀

Yes! obviously I’m always cheered up! 😛 that’s probably the easiest way to recognize me from any crowd lol! 😉

I do a lot of crazy random stuff! 😀

I truly enjoy helping others, teaching others new stuff, I’m not very good at teaching though, but I enjoy engaging in such activities to the fullest.
So basically whenever I’m blogging the same chemical reactions fires up in my brain which is responsible for the above, thereby almost all the time my blog articles ends up being a hyper active conversation lol! 😛

So you may find my blog articles UNPROFESSIONAL most of the time! but I DO NOT CARE! Hence blogging programming articles is something I do for fun and I enjoy it insanely. 😉 And yes this is probably going to be one of the weirdest tech-blogs you have ever seen given my unprofessional-blogging-style! lol 😉
Well I couldn’t care less as long as I share the knowledge across the articles, in a very friendly, easy to understand manner for even a high school kid could understand.

So you got any complains about the ÇøŋfuzëÐ SøurcëÇødë Blogging Style? Don’t bother complaining! 😀 As ÇøŋfuzëÐ SøurcëÇødë wouldn’t ever care! 😛

Cheers!

Stay Awesome fellas! 😀

One of the Greatest Secrets of My Life…

For me its not about Winning or Losing, Its about reaching my limits, going as far as I can go and then going farther… One of the greatest secrets of my life is, I never executed for victory against anyone else, or being better than anyone else…
I have always executed for the ultimate victory over myself, becoming the best I can be, breaking through my own impossibilities, redefining possibilities, and achieving greatness !

– ÇøŋfuzëÐ SøurcëÇødë
[Udara Alwis]

 

Winning a Special Award at ICTA e-Swabhimani Competition 2014

Oh yeah ! xD One of the most awesome moments in my entire life was when they announced… 😀

“ICTA e-Swabhimani competition’s e-Entertainment and Games section SPECIAL AWARD goes to Sri Lankan Newspaper Cartoons project by Udara Alwis ! “

OMG ! 😀 that moment of unexpectancy, thinking that I would have no chance among the big companies I competed with during the competition…

WP_20141105_22_50_59_Pro

WOHOOOOOOOOO ! 😀 Thank you very much Information and Communication Technology Agency of Sri Lanka (ICTA) and yes it was truly a wonderful event ! 😀

And this was me presenting on my project ‘Sri Lankan Newspaper Cartoons‘ in front of all the judges and competing Corporate giants… as a Finalist at ICTA e-Swabhimani Competition 2014 ! 😀

Link to Sri Lankan Newspaper Cartoons project –
http://lkpapercartoons.confuzed-sourcecode.com/

LogoBanner

 

You can Check out the Official Fan page of the Project here –
https://www.facebook.com/SriLankanNewspaperCartoonsProject

Slide1

 

Some Moments to Share…

Receiving the Special Award at ICTA e-Swabhimani all island competition for my Sri Lankan Newspaper Cartoons project ! 🙂

10441485_10152525533831977_6344200139861072666_n

 

That moment when you make your own Mother proud… :’)  !  Oh yeah so much of Amma points 😛

1907292_10152525535366977_2791329620654159984_n

Among the Winners at ICTA e-Swabhimani all island Competition… 🙂

10644963_10152525536016977_8166573454344299038_n

Sometimes you just gotta believe in yourself and follow your Dreams by yourself… despite of what everyone else tells you…
And someday you will end up there among the giants… 😉

WP_20141105_21_55_26_Pro

 

Some Blog posts regarding my project, Sri Lankan Newspaper Cartoons,

https://theconfuzedsourcecode.wordpress.com/2013/08/18/sri-lanka-newspaper-cartoons-gallery/

https://theconfuzedsourcecode.wordpress.com/2013/08/18/sri-lankan-cartoons/

https://theconfuzedsourcecode.wordpress.com/2014/11/03/welcome-to-confuzed-sourcecode-tech-innovations/

#SriLankanNewspaperCartoons   #SriLanka  #Newspaper   #Cartoon   #NewspaperCartoons  #ICTA