Tag Archives: 2D Graphics

I built an Interactive Color Picker Control for Xamarin.Forms!

Let me share my adventure of building an awesome interactive and responsive Color Picker UI Control for Xamarin.Forms with the help of a little SkiaSharp magic! 😉

To blow your mind, imagine something similar to the Color Picker your have in Ms Paint, HTML Web Color Picker or Google Search Web Color Picker…

Think of how interactive and fun to use those UI Elements are, with their drag and drop pointers on the color spectrum which picks up the color from wherever you drop it.

Why can’t we have the same easy to use fun interactive experience in our Xamarin.Forms apps?

Color Picker control is something that’s missing out of the box in Xamarin.Forms, even when it comes to 3rd party controls out there, neither of them are interactive or responsive, let along any fun to use all. lol 😀

Backstory…

Some time back, I ventured in a project where it required me to build a Color Picking UI element, where it would be easy to use for the user to have a similar experience to what we have with Ms Paint, or Web Color Picker UI elements. So I started off by looking at existing 3rd party library controls out there, which ended up me being disappointed seeing all the controls are just static boring color selection lists of grid style elements.

So I started building my own interactive fun-to-use Color Picker from scratch modeled after the Color Picker UI controls we have in Ms Paint, HTML Web Color Picker, etc… The awesomeness of this would allow you to touch, swipe and pan across a beautiful spectrum of color scheme and pick the color you desire! 😀

So… What?

So what we really need to build in this case is, create a Canvas with a full Color spectrum similar to a rainbow gradient effect spreading across, while allowing the User to touch at any given pixel point, up on which an event will trigger capturing the Color value of that pixel point. Also we should be able to highlight that touch triggered pixel point, giving the feedback to the User.

How? in a Gist…

Frankly this is not possible at all, out of the box in Xamarin.Forms, but with the help of a little SkiaSharp magic, this would be possible! SkiaSharp is the awesome 2D graphics rendering library that let’s you do all kinds of cool stuff on top of Xamarin.Forms. So basically we’re going to draw the full Color spectrum with a rainbow-gradient style spreading across a 2D canvas with the help of SkiaSharp.

We will define the list of main colors we need to include across the Canvas, while defining the Gradient fading effect between them. Then with regards to Touch, we need to enable this on the SkiaSharp canvas, and subscribe to the touch handling events.

Then given the User triggers a touch even on the Canvas, we will pick up those coordinate values on the canvas, and pick the Color values of the Pixel at that point on the Canvas. Voiala! We got the Color value picked by the User! 😉 Then as a responsive feedback we will draw highlighting circle around that pixel point coordinates on the Canvas. 😀

Well there you have it, quite straight forward eh! 😉

Sneak Peak!

Just to give a little sneak peak, here’s what I build… 😀 Behold the Interactive Color Picker Control for Xamarin.Forms!

Pretty awesome eh! Xamarin.Forms + SkiaSharp magic! 😉

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

Alright then let me show you how I built it…

Let’s start building!

Let’s begin by adding SkiaSharp to our Xamarin.Forms project. Open up Nuget Package Manager on your Xamarin.Forms solution node and add SkiaSharp.View.Forms Nuget to your .NET Standard project node and platform nodes as shown below…

That’s it, no extra set up is needed… 😉

Next we need to create our Custom Control, which I’m going to name as ColorPickerControl!

The ColorPickerControl!

It’s better to keep this in a dedicated folder in the .NET Standard project, inside a “Controls” folder, for the sake of clarity! 😉 So let’s create our ColorPickerControl as a type ContentView XAML element in the Controls folder…

<?xml version="1.0" encoding="utf-8" ?>
<ContentView
    x:Class="XFColorPickerControl.Controls.ColorPickerControl"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <!-- Content of the Control -->

</ContentView>

Then as of the code behind, let’s set up a PickedColor Property that holds the value of the Color that User picks during the run time, and an event that fires itself up on that action, PickedColorChanged event!

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ColorPickerControl : ContentView
{
	public event EventHandler<Color> PickedColorChanged;

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

	public Color PickedColor
	{
		get { return (Color)GetValue(PickedColorProperty); }
		set { SetValue(PickedColorProperty, value); }
	}

	public ColorPickerControl()
	{
		InitializeComponent();
	}
}

Alright next on to setting up the SkiaSharp bits in our Control…

The SkiaSharp magic!

SkiaSharp’s magical Canvas called SKCanvasView is what we’re going to use to Draw our Rainbow Color Spectrum and handle all the Touch event bits… So let’s begin by adding the SKCanvasView to our ColorPickerControl XAML and also the SkiaSharp.Views.Forms reference in the XAML itself..

<ContentView
    ...
    xmlns:skia="clr-namespace:SkiaSharp.Views.Forms;assembly=SkiaSharp.Views.Forms"
	...
	>

    <skia:SKCanvasView
        x:Name="SkCanvasView"
        EnableTouchEvents="True"
        PaintSurface="SkCanvasView_OnPaintSurface"
        Touch="SkCanvasView_OnTouch" />

</ContentView>

Code on Github: /XFColorPickerControl/Controls/ColorPickerControl.xaml

As you can see on my SKCanvasView element, I have enabled touch events with EnableTouchEvents property and subscribed to Touch event with SkCanvasView_OnTouch. Subscribing to PaintSurface allows us to draw full blown 2D graphics on the Canvas, which is why we have created the event SkCanvasView_OnPaintSurface event.

So let’s handle all those events in the code behind of our ColorPickerControl…

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ColorPickerControl : ContentView
{
	...
	
	private void SkCanvasView_OnPaintSurface
                      (object sender, SKPaintSurfaceEventArgs e)
	{
		var skImageInfo = e.Info;
		var skSurface = e.Surface;
		var skCanvas = skSurface.Canvas;

		var skCanvasWidth = skImageInfo.Width;
		var skCanvasHeight = skImageInfo.Height;

		skCanvas.Clear(SKColors.White);

		...
	}
	
	private void SkCanvasView_OnTouch
                      (object sender, SKTouchEventArgs e)
	{
		...
	}
}

Code on Github: /XFColorPickerControl/Controls/ColorPickerControl.xaml.cs

So we’re setting up the basic values we need to use inside SkCanvasView_OnPaintSurface with the skImageInfo, skSurface, skCanvas, which will be very useful in our next set of code snippets!

This is where our core implementation is going to be taking place, let me get into details of each code snippet one by one, but you can always go back to the full code on github and take a look by yourself… 😉 Let’s continue…

The Touch!

Let me begin diving in with the SkCanvasView_OnTouch event method implementation, which handles the touch events occurs on the SkiaSharp Canvas we added into our Control.

We need to keep a track on each Touch event that occurs, so we will store that in a local variable _lastTouchPoint which is of type SKPoint. Since we need to only consider the touch events that occur inside the canvas region, we’re validating each touch coordinate (X,Y) that comes into the event.

...
	private void SkCanvasView_OnTouch
	               (object sender, SKTouchEventArgs e)
	{
		_lastTouchPoint = e.Location;

		var canvasSize = SkCanvasView.CanvasSize;

		// Check for each touch point XY position to be inside Canvas
		// Ignore any Touch event ocurred outside the Canvas region 
		if ((e.Location.X > 0 && e.Location.X < canvasSize.Width) &&
			(e.Location.Y > 0 && e.Location.Y < canvasSize.Height))
		{
			e.Handled = true;

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

Based on the validated touch event coordinate, we’re firing up the SkiaSharp Canvas drawing cycle, SkCanvasView.InvalidateSurface(), where we will handle, picking up the color on the touch point and redrawing the canvas to highlight the touch point coordinates on the Canvas.

The Rainbow Color Spectrum!

So this right here is the most critical functionality that we need to implement, drawing the beautiful rainbow gradient color spectrum on our SkiaSharp Canvas. We’re going to draw the following list of colors across the spectrum, which values I picked up with the help of Google Web Color Picker..

Red | Yellow | Green (Lime) | Aqua | Blue | Fuchsia | Red
undefined

This will take place in our SkCanvasView_OnPaintSurface event method that we created in the previous step, where we create the Paint object that’s going to draw the color spectrum on the Canvas, along with the gradient fading effect between all the colors using SKShader object.

...
	private void SkCanvasView_OnPaintSurface
	               (object sender, SKPaintSurfaceEventArgs  e)
	{
		// Draw gradient rainbow Color spectrum
		using (var paint = new SKPaint())
		{
			paint.IsAntialias = true;

			// Initiate the primary Color list
			// picked up from Google Web Color Picker
			var colors = new SKColor[]
			{
				new SKColor(255, 0, 0), // Red
				new SKColor(255, 255, 0), // Yellow
				new SKColor(0, 255, 0), // Green (Lime)
				new SKColor(0, 255, 255), // Aqua
				new SKColor(0, 0, 255), // Blue
				new SKColor(255, 0, 255), // Fuchsia
				new SKColor(255, 0, 0), // Red
			};

			// create the gradient shader between Colors
			using (var shader = SKShader.CreateLinearGradient(
				new SKPoint(0, 0),
				new SKPoint(skCanvasWidth, 0),
				colors,
				null,
				SKShaderTileMode.Clamp))
			{
				paint.Shader = shader;
				skCanvas.DrawPaint(paint);
			}
		}
	}
...

As you can see we are defining the list of Colors with SKColor objects, that’ll populate the rainbow color spectrum on our Canvas. Then we use SKShader.CreateLinearGradient() method to build the gradient shader using the list of colors, and then we draw it on the Canvas using skCanvas.DrawPaint().

Keep a note how SKPoint() objects define the starting and ending coordinates on the Canvas which the shader will spread through, thus we’re taking skCanvasWidth picking the corner most value on the X axis. 😉

The Darker Gradient Strip!

Next we need to draw the darker shadow gradient strip on the Canvas allowing Users to pick the Darker Colors of the primary colors we defined.

We’re going to paint the darker color regions by drawing another layer on top of the previous drawn layer creating the illusion of darker regions of each color.

This will take place in our SkCanvasView_OnPaintSurface but below the code snippet that I showed before. Very much similar to the previous snippet, we’re doing almost the same thing but adding a darker gradient region at the bottom of the Canvas.

...
	private void SkCanvasView_OnPaintSurface
	               (object sender, SKPaintSurfaceEventArgs  e)
	{
		...
		
		// Draw darker gradient spectrum
		using (var paint = new SKPaint())
		{
			paint.IsAntialias = true;

			// Initiate the darkened primary color list
			var colors = new SKColor[]
			{
				SKColors.Transparent,
				SKColors.Black
			};

			// create the gradient shader 
			using (var shader = SKShader.CreateLinearGradient(
				new SKPoint(0, 0),
				new SKPoint(0, skCanvasHeight),
				colors,
				null,
				SKShaderTileMode.Clamp))
			{
				paint.Shader = shader;
				skCanvas.DrawPaint(paint);
			}
		}
	}
...

Here we’re drawing the darkening gradient layer starting from Transparent color to Black color across the Y axis, thus we’re taking skCanvasHeight picking the corner most value on the Y axis similar to what we did before. 😉

Here they are side by side, before and after drawing darker gradient strip… 😀

The Lighter Gradient Strip!?

This this is bit of an extra cherry on top, as you may have seen some of those Color Pickers include picking Lighter versions of the Colors. We can easily do this by adding a White color object to the list of colors in the code snippet I shared above.

...         
	...
		 ...
			// Initiate the darkened primary color list
			var colors = new SKColor[]
			{
				SKColors.White,
				SKColors.Transparent,
				SKColors.Black
			};  
		 ...
	...
...	

This will draw the secondary layer with White | Transparent | Black gradient effects on top of the full color spectrum layer.

There you go, with the Lighter color gradient strip. Although I wouldn’t include this in my demo app code 😛 Just coz I don’t like it! lol

Picking the Color on Touch!

This is the most crucial bit of this Control, also the most time consuming implementation I had to go through during my trial and error experimentation to get this working! 😮

We are going to be using the _lastTouchPoint SKPoint object, that we created before, in order to access the coordinate data of the touch point on Canvas. Then we look for extract the pixel color values on that coordinate on the Canvas, given that the Canvas is already rendered with the Color spectrum.

This will take place in our SkCanvasView_OnPaintSurface event method, below the color spectrum drawing code snippet.

Experimentation Phase…

Picking a pixel on the rendered Canvas layer is not a straight forward task, the idea here is to capture a quick snapshot of the Canvas graphic layer and convert that into a bitmap image, and use that image to pick the pixels from using the touch coordinates.

As you can see from below, the first implementation I put together which captures a snapshot of the Canvas surface layer and load it into a SKBitmap image, then I retrieve the Pixel data on that image using bitmap.GetPixel() by passing in the touch point values.

...
	private void SkCanvasView_OnPaintSurface
				   (object sender, SKPaintSurfaceEventArgs  e)
	{
		...
		
		// Picking the Pixel Color values on the Touch Point

		// Represent the color of the current Touch point
		SKColor touchPointColor;

		//// Inefficient: causes memory overload errors
		//using (var skImage = skSurface.Snapshot())
		//{
		//	using (var skData = skImage.Encode(SKEncodedImageFormat.Webp, 100))
		//	{
		//		if (skData != null)
		//		{
		//			using (SKBitmap bitmap = SKBitmap.Decode(skData))
		//			{
		//				touchPointColor = bitmap.GetPixel(
		//									(int)_lastTouchPoint.X, (int)_lastTouchPoint.Y);
		//			}
		//		}
		//	}
		//}
		
		...
	}
...

Later it started causing performance issues due to calling Snapshot() method during each rendering cycle, which is a very heavy process, and even sometimes overloads the memory.

Better Solution…

So after a bit more exploration with trial and error, I managed to build a solution based on a Xamarin Forum response that I found to a similar requirement I had…
https://forums.xamarin.com/discussion/92899/read-a-pixel-info-from-a-canvas

What if instead of taking a snapshot, we use SKImageInfo object of the Canvas instance and extract a SKBitmap image and read the pixel color data of the touch point coordinates. This is way more efficient and consumes much less memory for execution… 😉

...
	private void SkCanvasView_OnPaintSurface
				   (object sender, SKPaintSurfaceEventArgs  e)
	{
		...
		
		// Picking the Pixel Color values on the Touch Point

		// Represent the color of the current Touch point
		SKColor touchPointColor;

		// Efficient and fast
		// https://forums.xamarin.com/discussion/92899/read-a-pixel-info-from-a-canvas
		// create the 1x1 bitmap (auto allocates the pixel buffer)
		using (SKBitmap bitmap = new SKBitmap(skImageInfo))
		{
			// get the pixel buffer for the bitmap
			IntPtr dstpixels = bitmap.GetPixels();

			// read the surface into the bitmap
			skSurface.ReadPixels(skImageInfo,
				dstpixels,
				skImageInfo.RowBytes,
				(int)_lastTouchPoint.X, (int)_lastTouchPoint.Y);

			// access the color
			touchPointColor = bitmap.GetPixel(0, 0);
		}
		
		...
	}
...

As you can see we’re using skSurface.ReadPixels() to load the pixel data on the coordinates, and finally loading the exact pixel data into touchPointColor as a SKColor object type. 😀

So now we picked the Color from a given touch point on the Canvas, let’s move to the next bit…

The Touch Feedback!

This is the part where we provide on touch feedback for the User by highlighting the touch point on the Canvas up on each touch event. As you noticed we’re firing up the OnPaintSurface event upon each touch event of the Canvas, hence we can draw the highlighting region on the Canvas right here as a feedback loop.

We’re simply going to create a SKPaint object, with White color and use skCanvas.DrawCircle() to draw a circle around the touch point coordinates on the Canvas. Then as an added extra, I’m drawing another circle on top of it with the picked color, so that we can emphasize on the pixel color of the touch point. 😉

...
	private void SkCanvasView_OnPaintSurface
				   (object sender, SKPaintSurfaceEventArgs  e)
	{
		...
		
		// Painting the Touch point
		using (SKPaint paintTouchPoint = new SKPaint())
		{
			paintTouchPoint.Style = SKPaintStyle.Fill;
			paintTouchPoint.Color = SKColors.White;
			paintTouchPoint.IsAntialias = true;

			// Outer circle (Ring)
			var outerRingRadius = 
				((float)skCanvasWidth/
                    (float)skCanvasHeight) * (float)18;
			skCanvas.DrawCircle(
				_lastTouchPoint.X,
				_lastTouchPoint.Y,
				outerRingRadius, paintTouchPoint);

			// Draw another circle with picked color
			paintTouchPoint.Color = touchPointColor;

			// Outer circle (Ring)
			var innerRingRadius = 
				((float)skCanvasWidth/
                    (float)skCanvasHeight) * (float)12;
			skCanvas.DrawCircle(
				_lastTouchPoint.X,
				_lastTouchPoint.Y,
				innerRingRadius, paintTouchPoint);
		}
		
		...
	}
...

As you can see _lastTouchPoint X and Y coordinates to draw the circle, and we’re calculating the radius value for both circles by adjacent to Canvas width and height, so it renders nicely on any device scale.

And then to the final step, returning back the Color that we Picked from our ColorPickerControl!

Return the Picked Color!

Now we need to return back the Color value that the User picked, to the subscribers or whoever’s listening to the PickedColor property and PickedColorChanged event.

...
	private void SkCanvasView_OnPaintSurface
				   (object sender, SKPaintSurfaceEventArgs  e)
	{
		...
		
		// Set selected color
		PickedColor = touchPointColor.ToFormsColor();
		PickedColorChanged?.Invoke(this, PickedColor);
		
		...
	}
...

It’s as simple as setting the Value and firing up the Event with the new Color value parameter…

Alright, that’s it! We’ve finished building our awesome ColorPickerControl! 😀

Let’s try it out!

Since we created it as a standalone UI Control you can use this little awesomeness anywhere in your Xamarin.Forms project as you would with any UI element as easy as below…

<controls:ColorPickerControl 
	x:Name="ColorPicker"
	PickedColorChanged="ColorPicker_PickedColorChanged" />

So let’s try adding this to a ContentPage with a nice little Frame element around it with a fixed Height and Width…

<Frame
	x:Name="ColorPickerFrame"
	CornerRadius="8"
	HeightRequest="200"
	HorizontalOptions="Center"
	WidthRequest="350">
	<controls:ColorPickerControl 
		x:Name="ColorPicker"
		PickedColorChanged="ColorPicker_PickedColorChanged" />
</Frame>

This will give a nice little frame around the Color picker control, then on to the code behind…

private void ColorPicker_PickedColorChanged
			(object sender, Color colorPicked)
{
	ColorPickerHolderFrame.BackgroundColor = colorPicked;
}

PickedColorChanged provide you the picked Color value, so you can do what you wish with it!

Fire it up!

Time to fire it up yo! 😀 I’ve prepared a little demo app with my awesome ColorPickerControl for Xamarin.Forms, deployed for Android, iOS and UWP…

Android, iOS and UWP side by side working like a charm! 😀

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

The possibilities are endless, just a matter of your own creativity! 😉

Conclusion…

An interactive and responsive Color Picker is something that’s missing from Xamarin.Forms out of the box, even when it comes existing to 3rd party controls, there’s no such that fills the requirement, similar to MS Paint Color Picker, or HTML Web Color Pickers.

You can do all kinds of cool interactive 2D graphics rendering stuff with SkiaSharp on Xamarin.Forms, and thanks this, I managed to build a full fledged interactive and fun-to-use Color Picker UI Control, which is lacking in Xamarin.Forms ecosystem right now.

I’m planning to release a nuget package with this control quite soon, with a whole bunch of extra cool features embedded in 😉 So keep in touch!

Imagination is the limit yol! 😉

Share the love! 😀 Cheers!

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