Category Archives: App Development

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! 😉

Advertisements

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

A MVVM-styled Service for my Await-able Custom Input Dialogs (XFCustomInputAlertDialog)

So a lot of folks asked me regarding my previous post, An Await-able Transparent, Custom, Popup Input Dialog in Xamarin.Forms! 😉 how they could implement this awesomeness in a MVVM-friendly manner in Xamarin.Forms, instead of having to deal with dirty code-behind ugliness.

Frankly I did the above original implementation in a MVVM-manner, given myself being a MVVM-practitioner, but since there are a lot of newbie Xamarin devs out there, I thought it would help if I push it out there in the simplest manner for the newbies to understand without a hassle.

Anyhow in order to do some justice for the Xamarin-Forms-MVVM practitioners out there, including myself 😉 here I am pushing out how to implement the same awesomeness in Xamarin-Forms MVVM environment in a beautiful code manner! 😀 ❤

Service FTW!

When it comes to dealing with MVVM environments, Services are crucial, which is what we’re going to leverage our previous implementation to.

So we could call up this service from anywhere across our shared code.

This demonstration…

We shall be using Prism as the MVVM framework for this demo Xamarin.Forms project because its awesome! 😉

And create a Service implementation for our XFCustomInputAlertDialog, which we’ll be register with the Prism’s default IoC container.

Rest is pure magic! lol 😉

PS: I shall not be spoon feeding from this post about MVVM or how to set up MVVM framework in Xamarin.Forms, I shall assume you have solid knowledge on MVVM based Xamarin.Forms implementations. 🙂

If you want to be ahead of all, you can grab the Github code from here: https://github.com/UdaraAlwis/XFInputAlertDialogService

Yep this time I’ve created a separate repo for the project. Alright then let’s get started!

Let’s do it…

Taking a step by step approach…

1. Prism MVVM Setup

Add Prism for Xamarin.Forms to your project and do the primarily set up for Prism MVVM framework. (if you’re unaware of how to do this, there’s plenty of tutorials and blog posts online about setting up Prism for Xamarin.Forms)

This also means you’re to set up the Views and ViewModels for the Project. (ex: MainPage -> MainPageViewModel).

2. Set up XFCustomInputAlertDialog basics

There’s few basic things you need to set up from my previous post as follows, and you can go back take a look at that post for these steps,  An Await-able Transparent, Custom, Popup Input Dialog in Xamarin.Forms! 😉

  • Setting up Rg.Plugins.Popup library
  • Create InputAlertDialogBase control
  • Create your Custom Input Views as you wish
  • Manage code-behind of your Custom Input Views

That’s it! nothing more! Alright let’s get started off with leveraging to MVVM!

3. Creating the Service…

So we shall create the service for our Custom Alert Dialogs. We shall call it InputAlertDialogService, thereby start off by creating the interface, IInputAlertDialogService with required methods.

namespace XFInputAlertDialogService.Interfaces
{
    public interface IInputAlertDialogService
    { 
        /// <summary>
        /// Open Text Input Alert Dialog
        /// </summary>
        /// <param name="titleText"></param>
        /// <param name="placeHolderText"></param>
        /// <param name="closeButtonText"></param>
        /// <param name="validationLabelText"></param>
        /// <returns></returns>
        Task<string> OpenTextInputAlertDialog(
            string titleText, string placeHolderText,
            string closeButtonText, string validationLabelText);
			
	
	//add other types of dialog open methods from here..
	// Task<string> OpenCancellableTextInputAlertDialog(...)
	// Task<string> OpenSelectableInputAlertDialog(...)
	// ...
	// ...
    }
}

 

You can add any amount of Service method calls to the interface which you can use to implement the concrete implementation.

github.com/XFInputAlertDialogService/…/Interfaces/IInputAlertDialogService.cs

Next let’s create the concrete implementation of our service, InputAlertDialogService.

namespace XFInputAlertDialogService.Services
{
    public class InputAlertDialogService : IInputAlertDialogService
    {
        public async Task<string> OpenTextInputAlertDialog(
            string titleText, string placeHolderText,
            string closeButtonText, string validationLabelText)
        {
            // create the TextInputView
            var inputView = 
               new TextInputView(titleText, placeHolderText,
                   closeButtonText, validationLabelText);

            // create the Transparent Popup Page
            // of type string since we need a string return
            var popup = new InputAlertDialogBase<string>(inputView);

            // Add the rest of Popup 
	    // Dialog display code below...
	    // just as in XFCustomInputAlertDialog
	    // ...
        }

        //add other types of dialog open methods from here..
        // ...
    }
}

 

There we are inheriting from our interface and doing the necessary concrete implementation. You will add the Popup Dialog instantiating and pushing to the navigation stack logic as you did in XFCustomInputAlertDialog code. Since its going to be repeated I’m not going to post the same code snippet here.

You can take a quick peak in the Gitub Repo though 😉

github.com/XFInputAlertDialogService/…/Services/InputAlertDialogService.cs

Then we need to register our Service Interface and Concrete implementation in the Prism’s default Unity Container.

namespace XFInputAlertDialogService
{
	public partial class App : PrismApplication
	{
		public App
		(IPlatformInitializer initializer = null) :
		base(initializer) { }

		protected override void RegisterTypes()
		{
			...
			
			// services registration
		    Container.RegisterType<IInputAlertDialogService,
			InputAlertDialogService>();
		}
		
		...
	}
}

 

There you go, the service layer is now ready! 😀

4. Consuming the Service…

Now let’s consume our Custom Popup Dialog Service in the ViewModel. First let’s inject it to the ViewModel and prepare it to be used when you need it.

public class MainPageViewModel 
	: BindableBase, INavigationAware
{
	private readonly 
	IInputAlertDialogService _inputAlertDialogService;
	
	public MainPageViewModel(
	IInputAlertDialogService inputAlertDialogService)
	{
		...
	
		_inputAlertDialogService = inputAlertDialogService;
		
		...
	}

        ...
}

 

Thanks to the IoC pattern, look at that beautiful and clean code. 😉

Now you’re ready to invoke the awesome custom popup dialogs from anywhere in your ViewModel. Let’s do that as the final step, shall we?

var result = await 
	_inputAlertDialogService.OpenTextInputAlertDialog(
	"What's your name?",
	"enter here...", 
	"Ok",
	"Ops! Can't leave this empty!");

 

If you don’t get the hint, you can simply create a Command in your ViewModel and bind that to a Button or something in your View and add the above call to the Command’s execution method as shown below. 😉

public DelegateCommand 
		OpenTextInputAlertDialogCommand { get; set; }

public MainPageViewModel(
	IInputAlertDialogService inputAlertDialogService)

{
	...
	
	OpenTextInputAlertDialogCommand = new DelegateCommand(OpenTextInputAlertDialog);
	
	...
}

private async void OpenTextInputAlertDialog()
{
	var result = await 
		_inputAlertDialogService.OpenTextInputAlertDialog(
		"What's your name?",
		"enter here...", 
		"Ok",
		"Ops! Can't leave this empty!");
}

 

There you go pure MVVM-Xamarin.Forms goodness! 😀

If you’re one of the lazy you can grab the whole code from Github: https://github.com/UdaraAlwis/XFInputAlertDialogService

Well fellas, that’s it!

Enjoy! 😀 Share the love!

-Udara Alwis 😀

An Await-able Transparent, Custom, Popup Input Dialog in Xamarin.Forms! ;)

Imagine you wanted to prompt your user with a popup alert dialog (which is also transparent, because its cool! lol) 😉 asking them to enter some value and you want to await the whole task (make it awaitable) while you’re at it, so the execution will halt until the user enter the value, and then retrieve the user entered value to the point of origin? 😀

And just to add some sugar to it, may be you wanted to customize and decorate the appearance of the input view?

Something like this?

Seems pretty cool yeah! That’s what I’m gonna share today!

Right outta Xamarin.Forms?

Now there’s no way you could do either of those things in that scenario right out of Xamarin.Forms! Nope, not with a Modal Popup, which doesn’t support transparency, and not even with DisplayAlerts or ActionSheets, since the’re not customizable, they don’t allow text input or any kind of custom input view, only multiple button selections.

So how could I do it?

Let me explain fellas!

So for transparency and ultimate flexibility of setting up custom popup views, we are going to use the awesome Rg.Plugins.Popup library for Xamarin.Forms and to make the whole Task awaitable let’s use a TaskCompletionSource (Thank you dot net)! 😉

So the trick here for adding custom input views to the popup page, is by creating our Xamarin.Forms custom views using a ContentView and set them to the Content of popup page.

Alright then time for some coding!

Let the coding begin…

But first, setting up!

First thing first create a Xamarin.Forms PCL project in Visual Studio. 🙂

Then install Rg.Plugins.Popup library for Xamarin.Forms through Nuget Package manager.

I’ve actually written a blog post about Rg.Plugins.Popup in my blog right here: So I created a Popup with Transparent background in Xamarin Forms… 😉

Create the Transparent Popup Page…

Once you’re done with that, let’s create our custom Transparent Popup Page using the Rg.Plugins.Popup we just installed.

Something to keep in mind,

  • We should allow it to use Generic data types as for the return data type. 😀
  • Popup page provides us with many cool features, including Page background click handling and back button press handling, which we will override as of disable page background click to dismissal and disable back button press cancellation.
  • Pass in a View and set it to the PopupPage’s Content property, which we will attach the custom input view we want to use in our popup page.
  • Set the transparency level to 0.4 of alpha value.

Let’s call it InputAlertDialogBase.

/// <summary>
/// The awesome Transparent Popup Page
/// sub-classed from Rg.Plugins.Popup
/// Customized for our usecase with
/// Generic data type support for the result
/// </summary>
/// <typeparam name="T"></typeparam>
public class InputAlertDialogBase<T> : PopupPage
{
	public InputAlertDialogBase(View contentBody)
	{
		Content = contentBody;

		this.BackgroundColor = new Color(0, 0, 0, 0.4);
	}

	// Method for animation child in PopupPage
	// Invoced after custom animation end
	protected override Task OnAppearingAnimationEnd()
	{
		return Content.FadeTo(1);
	}

	// Method for animation child in PopupPage
	// Invoked before custom animation begin
	protected override Task OnDisappearingAnimationBegin()
	{
		return Content.FadeTo(1);
	}

	protected override bool OnBackButtonPressed()
	{
		// Prevent back button pressed action on android
		//return base.OnBackButtonPressed();
		return true;
	}

	// Invoced when background is clicked
	protected override bool OnBackgroundClicked()
	{
		// Prevent background clicked action
		//return base.OnBackgroundClicked();
		return false;
	}
}

 

There you go, over to the next step!

Configure the await-able Task properties…

So let’s create a Task and TaskCompletionSource inside our InputAlertDialogBase, to handle await-ability of our “Transparent, Custom, Popup Input Dialog” as I’ve mentioned in the blog title! 😉

public class InputAlertDialogBase<T> : PopupPage
{
	// the awaitable task
	public Task<T> PageClosedTask { get { return PageClosedTaskCompletionSource.Task; } }

	// the task completion source
	public TaskCompletionSource<T> PageClosedTaskCompletionSource { get; set; }

	public InputAlertDialogBase(View contentBody)
	{
		...

		// init the task completion source
		PageClosedTaskCompletionSource = new System.Threading.Tasks.TaskCompletionSource<T>();

		...
	}

	...
}

 

Note that how we are initializing the TaskCompletionSource in the Constructor.

Alright, now our Transparent Popup is ready. Next we need to construct the Custom Input View, that we are going to pass into the InputAlertDialogBase to display and retrieve data input (text or any kind) from the User. 😀

Create your Custom Input View! 😀

Alright this step is totally up to your desires, you could construct any kind of a Custom Input View to be displayed on top of the InputAlertDialogBase we just created above, and retrieve the User’s inputs.

So for this example, let’s create a simple View with Title Label, Text Entry and Ok button yeah! 😉 Also let’s add a simple validation Label inside it to show up if the User tries to leave the Text Entry empty and hit the ok button to quit.

<?xml version="1.0" encoding="UTF-8" ?>
<ContentView
    x:Class="XFCustomInputAlertDialog.InputViews.TextInputView"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <ContentView.Content>
        <StackLayout
            Padding="10"
            BackgroundColor="White"
            HorizontalOptions="CenterAndExpand"
            Spacing="5"
            VerticalOptions="CenterAndExpand">
            <Label
                x:Name="TitleLabel"
                FontSize="Medium"
                Text="Enter the value:" />
            <Label
                x:Name="ValidationLabel"
                FontSize="Micro"
                IsVisible="False"
                Text="You can't leave this field empty!"
                TextColor="Red" />
            <Entry x:Name="InputEntry" Placeholder="Enter Here..." />
            <Button x:Name="CloseButton" Text="Ok">
                <Button.HeightRequest>
                    <OnPlatform x:TypeArguments="x:Double">
                        <On Platform="Android" Value="40" />
                        <On Platform="iOS" Value="30" />
                    </OnPlatform>
                </Button.HeightRequest>
            </Button>
        </StackLayout>
    </ContentView.Content>
</ContentView>

 

As you can see we have created a simple ContentView with a custom Text input view! 😀

Notice that we have explicitly named all the elements and added a button click event, this is to make it easy to set custom textual values to the elements and to handle the OK button’s click event as for the closing of the Popup Page. 🙂

Pretty simple yeah, next let’s handle the back end of this custom View to manage the Textual values, Ok button’s click event and validations.

Let’s manage code-behind of Custom Input View…

Now this is important, if you consider a ContentView, all it’s Child elements are private to it’s class scope, so we can’t observe or interact with any of the property value changes or behaviors from outside of the View.

Therefore we need to create custom properties that will expose those required values and events to the public.

Something to keep in mind here,

  • In order to customize the values displayed in the Child elements of the ContentView (Label,Button, etc..) we should pass in the values to the Constructor and set them to the Child elements there.
  • We should create a public EventHandler to handle the Ok Button’s click event from outside the View and add a public string Propery to expose the text Entry’s value to the public.
  • Subscribe to the Entry’s TextChanged event to reflect the value the public string property.
  • Create a public bindable Boolean property to display or hide Validation label in the ContentView. Or you could handle this internally in the View on the Ok Button’s click event as well, but it would be nice if we could expose the Validations to public so we could handle it outside the View.

public partial class TextInputView : ContentView
{
	// public event handler to expose 
	// the Ok button's click event
	public EventHandler CloseButtonEventHandler { get; set; }

	// public string to expose the 
	// text Entry input's value
	public string TextInputResult { get; set; }

	public TextInputView(string titleText, 
          string placeHolderText, string closeButtonText, 
           string validationLabelText)
	{
		InitializeComponent();

		// update the Element's textual values
		TitleLabel.Text = titleText;
		InputEntry.Placeholder = placeHolderText;
		CloseButton.Text = closeButtonText;
		ValidationLabel.Text = validationLabelText;

		// handling events to expose to public
		CloseButton.Clicked += CloseButton_Clicked;
		InputEntry.TextChanged += InputEntry_TextChanged;
	}

	private void CloseButton_Clicked(object sender, EventArgs e)
	{
		// invoke the event handler if its being subscribed
		CloseButtonEventHandler?.Invoke(this, e);
	}

	private void InputEntry_TextChanged(object sender,
					TextChangedEventArgs e)
	{
		// update the public string value 
		// accordingly to the text Entry's value
		TextInputResult = InputEntry.Text;
	}
}

 

So you can see we are passing in all the required values to set to our Child element’s we are passing in to the Constructor and setting them up there. Also we are subscribing to the Ok Button’s OnClick event and text Entry’s TextChanged event.

Inside the CloseButton_Clicked() event we are invoking the public EventHandler CloseButtonEventHandler if it’s being subscribed to by outside.

As well as  the Entry’s InputEntry_TextChanged() event we are updating the public TextInputResult to reflect the Entry’s text value to the public.

Don’t forget to handle Validations…

Oh and here’s the Bindable Boolean property you should include inside the TextInputView code behind to handle the Validations from outside the View.

public partial class TextInputView : ContentView
{
	...
	
	public static readonly BindableProperty 
           IsValidationLabelVisibleProperty =
		BindableProperty.Create(
			nameof(IsValidationLabelVisible),
			typeof(bool),
			typeof(TextInputView),
			false, BindingMode.OneWay, null,
			(bindable, value, newValue) =>
			{
				if ((bool)newValue)
				{
					  
		((TextInputView)bindable).ValidationLabel
					 .IsVisible = true;
				}
				else
				{
					 
		((TextInputView)bindable).ValidationLabel
					.IsVisible = false;
				}
			});

	/// <summary>
	/// Gets or Sets if the ValidationLabel is visible
	/// </summary>
	public bool IsValidationLabelVisible
	{
		get
		{
			return (bool)GetValue(
                             IsValidationLabelVisibleProperty);
		}
		set
		{
			SetValue(
                         IsValidationLabelVisibleProperty, value);
		}
	}
	
	...
}

 

Now speaking of the bindable IsValidationLabelVisibleProperty, we are updating the Validation Label’s visibility based on its value changes accordingly. 🙂

Following this method, you can create any kind of custom Input Views to be attached to our Transparent Popup Page. 🙂 All you need to do is expose the required Values and Events to the public.

Alright next step…

Time to assemble everything and consume it!

Now we are going to put everything together and get it to be used as our “awaitable Transparent, Custom, Popup Input Dialog”! 😉

Somethings to keep in mind here,

  • We need to initialize our TextInputView by passing in the parameters we would like the necessary child elements to display
  • Create an InputAlertDialogBase<string>(), yes of type string, since we are going to return a string from the Popup Alert.
  •  Subscribe to the CloseButtonEventHandler of TextInputView’s instance to handle validation and reflect the Text input value to the TaskCompletionSource.
  • Push the popup page instance to Navigation Stack and await the page’s Task
  • Upon result retrieval Pop the page from Stack and return the user inserted value.

Alright let’s do it…

private async Task<string> LaunchTextInputPopup()
{
	// create the TextInputView
	var inputView = new TextInputView(
		"What's your name?", "enter here...", 
		"Ok", "Ops! Can't leave this empty!");

	// create the Transparent Popup Page
	// of type string since we need a string return
	var popup = new InputAlertDialogBase<string>(inputView);

	// subscribe to the TextInputView's Button click event
	inputView.CloseButtonEventHandler +=
		(sender, obj) =>
		{
			if (!string.IsNullOrEmpty(
                         ((TextInputView)sender).TextInputResult))
			{
				
                            ((TextInputView)sender)
                               .IsValidationLabelVisible = false;
				
                            // update the page completion source
                            popup.PageClosedTaskCompletionSource
                                .SetResult(
                                ((TextInputView)sender)
                                      .TextInputResult);
			}
			else
			{
				
                             ((TextInputView)sender)
                                 .IsValidationLabelVisible = true;
			}
		};

	// Push the page to Navigation Stack
	await PopupNavigation.PushAsync(popup);

	// await for the user to enter the text input
	var result = await popup.PageClosedTask;

	// Pop the page from Navigation Stack
	await PopupNavigation.PopAsync();

	// return user inserted text value
	return result;
}

 

There you go, step by step as I explained before you can see how it’s being consumed. Specially inside the CloseButtonEventHandler, every time the event fires we are checking the TextInputResult property and enabling or disabling the IsValidationLabelVisible property, as well as updating the PageClosedTaskCompletionSource property value if a text value is being entered by the User, which will in return update the awaiting PageClosedTask and task will proceed to completion state, then return the value after popping the Page. 😀

There you go! 😀 How straight forward is that! 😉

Keep in mind like I said before you can add any kind of a customized View on top of our Transparent Popup Page, and retrieve any kind of result as you expect from the User following the same steps. 😀

Let’s see this in action…

 

Look at that coolness right! 😉

Since it’s full on Xamarin.Forms, and doesn’t have a single line of native code, you could straight up run this implementation on all Android, iOS, UWP, WinPhone as you wish! 😀

I want more! 😮

Alright now that’s just a little bit of basic head start of what you could do, whereas if you get creative and smart you could do a lot more cool stuff like this…

  

 

 

There you have it, some cool stuff I played around with my implementation. 😉

You can grab the Github code from here: github.com/UdaraAlwis/XFCustomInputAlertDialog

Well fellas, that’s it for now!

Enjoy! 😀 Share the love!

-Udara Alwis 😀

Wait… How could I handle Click event of a Custom Renderer Button in Xamarin Forms ? :|

Now we all know how Xamarin allows your to override the renderering process of any given UI control from native level and do any sort of modifications through Custom Renderers.

Completely overriding Xamarin Forms Control in Custom Renderer?

It even allows you to completely override the whole Control that’s associated with Xamarin Forms type Control and replace it with a completely native type Control. Specifically in cases like where you override the Control property with SetNativeControl() method in your Custom Renderer.

But when you do that…

But what happens when you complete replace and override the associated default control for your renderer is that, you will lose the access to Events of that particular control.

To be specific…

Let’s take a look at the following Custom Renderer…

[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class CustomButtonRenderer : ButtonRenderer
    {
        protected override async void OnElementChanged(ElementChangedEventArgs<CustomButton> e)
        {
            base.OnElementChanged(e);
            
            if (e.NewElement != null)
            {
		Android.Widget.Button nativeButton = new Android.Widget.Button();
			
                SetNativeControl(nativeButton);
            }
        }
     }
}

 

There you can see we are completely replacing the default Button Control associated with the Renderer with our own native Button control.

When you do that, since you’re completely replacing everything, you will lose access to all the events and properties associated with the default control. Such as Button Click, Touch Events and so on.

As in try to subscribe to your CustomButton’s default Clicked event, it won’t fire up during run time, since it been overridden by the native button control.

So how to handle events?

Yep in that case, we need to handle those events manually and map those necessary events from our Native button control to Xamarin Forms level properties and events.

Custom Events…

Yep this is how you manually create an Event for your Custom Button.

public class CustomButton : Button
{
	public event EventHandler ClickedCustom;
	
	public void SendCustomClicked()
	{
		EventHandler eventHandler = this.ClickedCustom;
		eventHandler?.Invoke((object)this, EventArgs.Empty);
	}
}

 

And then upon the Native Button’s Click event we invoke this event from the Custom Renderer level. 🙂

nativeButton.ClickEvent += (sender, args) =>{
	view.SendCustomClicked();
}

 

And then at the run time it will fire up the ClickedCustom event for your Custom Button in response of the native button’s click.

So now you can subscribe to ClickedCustom event instead of default Clicked event in your Xamarin Forms code and get the response upon the custom button click.

Any other type of events and properties…

You could follow the same pattern for any other type of event you wish to handle, and even properties such as Text, Color and blah blah… 😉

TADAAA! 😀

Enjoy!

A Cool Breadcrumbs Bar with Xamarin Forms Animations…

A Breadcrumbs bar? Bread? Crumbs? Breadcrumbs? Ok I don’t wanna make you hungry right now! 😛

le Breadcrumbs bar…

But hey you know the Breadcrumbs bar we use in our UI designs! that bar kind of thingy that they put up, to indicate Navigation steps in Websites and mobile applications(not often though). Yeah that one, exactly! 😀

So the other day I had to implement a Breadcrumbs bar control with some nice animations to one of our Xamarin Forms apps… First I was like, Breadcrumbs bar? they actually use them in Mobile Apps? Well turned out to be YEAH! some still do! lol 😛

So I thought, why not give a try to Xamarin Forms Animations while I’m at it, without diving in to the native level to handle all the nice animations.

So as a result of that, let me introduce you to the Cool Breadcrumbs Bar cooked right out of Xamarin Forms Animations. 😉

This Breadcrumbs Bar control can be used to show case navigation path in your Xamarin Forms mobile applications, and you could use this as a separate ui control and add it to each page in your app, and set it to nicely animate and showcase breadcrumbs path in those pages. 😀

Now how did I do it?

In simple theory, I created a StackLayout control, which adds Labels horizontally on demand, but when the Labels are added to the StackLayout, they are being added with a nice X axis point transformation from right end of the screen to the left end using Xamarin Forms Animations. Likewise, each breadcrumb gets added next to each other one by one on demand.

breadcrumbs-completed

^^ Yep that’s the actual Breadcrumbs bar control I implemented with Xamarin Forms! 😉

Now I must inform you for the sake of the post I have done a simple implementation in a sample code, since I can not share the original implementation I did for my company project. So you should be smart enough to extract this implementation into another control and use it as a component for your pages. 😛

Now if you’re one of em lazy people, then grab my github up in here : XFBreadcrumbsBar

Let’s get into coding.

Alright create your Xamarin Forms PCL project and follow me!

namespace WhateverYourNamespace
{
    public class HomePage : ContentPage
    {
        private StackLayout _breadcrumbStackLayout;
        private ScrollView _breadCrumbsScrollView;
        private Button _addNewBreadcrumbButton;
        private Button _clearAllBreadcrumbsButton;

        public HomePage()
        {
           
        }
    }
}

 

Alright we create the HomePage and make sure to add those initial elements which we will be using later.

Create the Breadcrumbs Bar

Next lets create our simple but awesome Breadcrumbs bar implementation with the above StackLayout and ScrollView.

// le animated breadcrumbs bar
_breadcrumbStackLayout = new StackLayout()
{
	Orientation = StackOrientation.Horizontal,
	HorizontalOptions = LayoutOptions.FillAndExpand,
	Children =
	{
		new Label
		{
			HorizontalOptions = LayoutOptions.Start,
			Text = "Welcome!",
			FontSize = 15,
			FontAttributes = FontAttributes.Bold,
			TextColor = Color.Black,
		},
	},
	Padding = new Thickness(10,0,10,0),
	HeightRequest = 30,
};
_breadcrumbStackLayout.ChildAdded += AnimatedStack_ChildAdded;

// let's add that breadcrumbs stacklayout inside a scrollview
_breadCrumbsScrollView = new ScrollView
{
	Content = _breadcrumbStackLayout,
	Orientation = ScrollOrientation.Horizontal,
	VerticalOptions = LayoutOptions.StartAndExpand,
};

 

Now let me do a bit of explaining there, I have created StackLayout with Horizontal Orientation so that we could stack up our breadcrumb Labels next to each other. Then I have added a Label as the first child to showcase the first default Breadcrumb in the bar. 🙂

Next I have wrapped the StackLayout inside a ScrollView, to allow the new Breadcrumbs to be visible in case the Breadcrumbs StackLayout gets filled and more breadcrumb Labels are to be added. So that we could scroll to the end of the Breadcrumbs StackLayout and make them visible. 😉

Then notice I have subscribed the to ChildAdded event? yep that’s to handle new Breadcrumbs being added at the runtime, which we will get into later. 😀

Add the rest of tid bits for the UI

Next let’s add a title to the page and two buttons to show case the awesome Breadcrumbs bar, then put them all together into the Content of the page.

// Button for adding and removing breadcrumbs 
_addNewBreadcrumbButton =
	new Button()
	{
		Text = "Add a Breadcrumb",
		TextColor = Color.Black,
		BackgroundColor = Color.White,
		BorderColor = Color.Gray,
		BorderWidth = 2,
	};
_addNewBreadcrumbButton.Clicked += AddNewBreadcrumbButtonOnClicked;

_clearAllBreadcrumbsButton =
	new Button()
	{
		Text = "Clear Breadcrumbs",
		TextColor = Color.Black,
		BackgroundColor = Color.White,
		BorderColor = Color.Gray,
		BorderWidth = 2,
	};
_clearAllBreadcrumbsButton.Clicked += ClearAllBreadcrumbsButtonOnClicked;


// Now put em all together on the screen
Content =
new StackLayout()
{
	Padding = Device.OnPlatform(
	new Thickness(5, 40, 5, 0), 
	new Thickness(0, 20, 0, 0), 
	new Thickness(0, 20, 0, 0)),
	Orientation = StackOrientation.Vertical,
	Children =
	{
		_breadCrumbsScrollView,
		
		new Label()
		{
			VerticalOptions = LayoutOptions.EndAndExpand,
			HorizontalTextAlignment = TextAlignment.Center,
			Text = "Welcome to the Breadcrumbs Bar with Xamarin Forms !",
			FontSize = 25,
			TextColor = Color.Black,
		},

		new StackLayout() { 
			Children = { 
				_addNewBreadcrumbButton,
				_clearAllBreadcrumbsButton,
			},
			VerticalOptions = LayoutOptions.End,
			Padding = new Thickness(10,10,10,10),
		}
	}
};

BackgroundColor = Color.White;

 

Alright no need to spoon feed this part I suppose, since the basic Xamarin Forms stuff. Those Button click events we will handle next! 😉

Adding a new Breadcrumb?

Don’t you worry child! Here’s the button click event I talked about earlier, AddNewBreadcrumbButtonOnClicked.

private void AddNewBreadcrumbButtonOnClicked(object sender, EventArgs e)
{
	_addNewBreadcrumbButton.IsEnabled = false;

	// retrieve the page width
	var width = Application.Current.MainPage.Width;

	// Add the new Breadcrumb Label
	_breadcrumbStackLayout.Children.Add(new Label
	{
		// Grab some random text (as in insert whatever 
		// the text you want for your new breadrumb)
		Text = "/ " + 
		RandomWordGenerator.GetMeaninglessRandomString(new Random().Next(5, 10)),
		FontSize = 15,
		TextColor = Color.Black,
		TranslationX = width,
	});

	// Scroll to the end of the StackLayout
	_breadCrumbsScrollView.ScrollToAsync(_breadcrumbStackLayout,
		ScrollToPosition.End, true);

	_addNewBreadcrumbButton.IsEnabled = true;
}

 

Now here is where we add the new Breadcrumbs to the Breadcrumbs Bar StackLayout at run time. Pretty simple right?

Ok when you click on the “Add a Breadcrumb” button, it will first retrieve the Screen Width and then create a Label which represents a Breadcrumb and add some dummy text to it. Oh by the way to generate a dummy text I’m using this super simple static class which I created earlier you can grab it in this post : Random String Generator 

Then we are setting it’s TranslationX property to the Width of the screen, which will place this Label at the edge of the Breadcrumbs Bar StackLayout.

After adding the Label, next we are scrolling the ScrollView to the end to make the transition visible for the new Breadcrumb Label.

Now you should keep in mind that,

You can add any type of Breadcrumbs to the breadcrumbs bar, such as Buttons, Images etc… and make it look even more cooler! 😉

Next is the beautiful Animation part….

Awesome Animation…

So this is the most important part where we are animating out the Breadcrumb Label getting added to the Breadcrumbs Bar.

private void AnimatedStack_ChildAdded(object sender, ElementEventArgs e)
{
	Device.BeginInvokeOnMainThread(() =>
	{
		var width = Application.Current.MainPage.Width;

		var storyboard = new Animation();
		var enterRight = new Animation(callback: d => 
		_breadcrumbStackLayout.Children.Last().TranslationX = d,
		start: width,
		end: 0,
		easing: Easing.Linear);

		storyboard.Add(0, 1, enterRight);
		storyboard.Commit(
		_breadcrumbStackLayout.Children.Last(), 
		"RightToLeftAnimation", length: 800);
	});
}

 

So to explain a bit we are using a compound animation to animate the Breadcrumb Label’s X position from the starting point to the 0th point of the screen. Since we originally set the X position to the edge of the Screen, now we can decrease it through an Animation and bring it to the position it should be placed, which is next to the previous Child in the _breadcrumbStackLayout. 

This gets fired whenever you click on the  “Add a Breadcrumb” button and a new child gets added to the StackLayout, resulting a beautiful animation from right end of the screen to the left.

PS : You can play around with the Easing of the Animation and the timing to add beautiful animation to it. Use your imagination and go crazy! 😉

Clear the Breadcrumbs!

This is super easy!

private void ClearAllBreadcrumbsButtonOnClicked(object sender, EventArgs eventArgs)
{
	_breadcrumbStackLayout.Children.Clear();

	_breadcrumbStackLayout.Children.Add(
	new Label
	{
		HorizontalOptions = LayoutOptions.Start,
		Text = "Welcome!",
		FontSize = 15,
		FontAttributes = FontAttributes.Bold,
		TextColor = Color.Black,
	});
}

 

Just get rid of the Children in the StackLayout and add the default Breadcrumb back if you wish like I have chosen above 😉

Next is Run time!

That’s it fellas, hit F5 and watch the magic! 😀

breadcrumbs-bar-android  breadcrumbs-bar-ios

Well here’s the cool Breadcrumbs Bar control I added in my project after all the customization. 😉

screen-shot-2017-01-26-at-7-17-11-pm screen-shot-2017-01-26-at-7-17-22-pm

Here’s a little tip, I basically moved the Breadcrumb related stuff to a custom control and used them in all the app pages. So now whenever we navigate to any page the breadcrumbs bar will nicely animate itself at the page visible event. 😉

breadcrumbs-completed

So your imagination is the limit fellas!

Enjoy! 😀

The three awesome tools by Xamarin! Workbooks|Profiler|Inspector

Last Friday (20th January, 2017) I did a tech talk at Singapore Mobile .Net Developers  meetup, under the topic “The three Awesome tools by Xamarin – Workbooks/Inspector/Profiler”!

So this blog post is a recap of the stuff I talked about! 😉

First of all here are the slides.

Here we go, the recap…

The three awesome tools by Xamarin

slide1

Last few months Xamarin has been busy releasing a lot of new updates and tools for us Developers, specially since the acquisition by Microsoft, they have been exponentially improving their platform and eco-system. 😀

So today I thought of picking up three awesome tool that has been released by Xamarin last few months, which are going to be extremely useful for Xamarin Mobile Development.

slide3

So to start off with…

Xamarin Workbooks!

slide4

Why do we need Xamarin Workbooks you asked? 😮

slide5

Now Imagine you’re someone who’s trying to learn Xamarin Mobile development or may be even C# dot net development? 😀

Could be someone trying to teach someone Xamarin or dot net or may be you’re trying to demo some awesome piece of code you implemented at a presentation, along with some documentation? 😉

Or simply you’re just trying out an experimenting some piece of code before you do some actual implementation in your actual project code?

Now in all of these stations, you have to open up your IDE, open up the documentations or presentations may be and most annoyingly you have to continuously switch in between them at all times. Not to mention having to recompile and run your code at the same time you switch back and forth. 😮

Oh well what a hassle is that?

To get rid of all that hassle, we have Xamarin Workbooks now! 😉

slide6

A perfect blend of documentation and code and immediate live preview results.

Xamarin Workbooks, is a prefect solution for experimenting with Xamarin and dot net code implementations and even as a learning tool for exploring code snippets and various kinds of implementations in Xamarin and dot net.

Perfect for creating teaching guides with a sweet side by side integration of code and documentation. Whenever you create or open up a Workbook, it creates a Sandbox environment for you to do your stuff, so you could accomplish your documentation aspect and coding aspect in one single place. 😉

slide7

So workbooks packs a bunch of awesome features, such as full fledged code editor with Roslyn IntelliSense, which has similar syntax coloring just like in Visual Studio. It has in-line compiler diagnostics support as well.

Attached with a rich text editor for you to add side by side code and documentation on the go. You could also easily search and add nuget packages as you go, just like you would do in Visual Studio, and instantly preview the results in console, or any mobile emulators as you have chosen.

You can easily save an share your workbooks with anyone and they could open it up and try out as they wish.

slide12

So Xamarin Workbooks supports dot net console/WPF implementations, Xamarin Android/iOS mobile development and even Xamarin Mac development scenarios. How cool is that eh! 😉

Xamarin Profiler!

slide14

Why do we need Xamarin Profiler you asked? 😮

slide15

Now as mobile developers we need to make sure we are giving a smooth intuitive user experience for our beloved users. So in order to do that, we need to make sure our app is fully optimized for the memory usage, process usage and various resource usage without causing any excessive lags or crashes.

And even some times during the development we come across these mysterious crashes without even hitting any debug points where we need more than just the debug logs to figure out what’s causing those mysterious crashes. 😮

Another aspect is that as mobile developers we need to always focus on the over flow of the resource usage in our application at run time so that we could do the necessary improvements in our code to reduce any excessive resource usage.

Something very important to keep in mind is that when we are dealing with Xamarin Mobile Development, we have to deal with both the Xamarin dot net environment and the Native environment at run time. In that case the available native profilers we have for android and ios can not help to analyze our xamarin dot net environment. So we need something better than just native profilers for our Xamarin Mobile applications.

As a solution for all those scenarios, we have Xamarin Profiler now! 😉

slide16

Xamarin Profiler is a tool that seamlessly integrated with your Xamarin Application, collects and displays information to analyze your application at run time.

This can easily be used for finding memory leaks, resolving performance issues, monitoring resource usage at the run time, and more over to polish up your mobile app before delivering to your users.

Fun fact, is that this tool is actually based on the Mono log profiler which is a command line profiler that they previously used to analyze Mono run time applications. So what they have done is, they’ve added a bunch of improvements to it and added this intuitive UI on top of it deliver this analytical information for us developers! 😀

slide17

So there are three key features or as they call them “instruments” that’s packed along with Xamarin Profiler. 😀

Allocations instrument is used for analyzing  the memory usage of your application at any given point of time at the run time.

Time Profiler instrument is used for tracking app performance, whereas it allows you to see which function took the longest to finish its execution.

Then we have the Cycles instrument, which provides you details with memory cycles occurred at the run time. May be I should explain it a bit further…

Memory Cycles: When you’re dealing with Xamarin Mobile applications, we have this environment of managed dot net environment and the un-managed native environment, sometimes due to our bad code a bunch of objects in the memory creates references to them selves in a circular manner, which could happen inside the dot net environment or most of the time in between the dot net and the un-managed environment. So in situations like that, the Garbage collector finds it hard to break through those circular references and release those objects, which results in those objects presisting in memory and the memory usage is only going to get increased. 🙂

So thanks to Xamarin Inspector we could easily identify those memory cycles and do the necessary changes in our code to eliminate them 😉

slide18

It also packs up these additional features allowing us to further drill down into details to analyze our application run time.

Xamarin Inspector!

slide20

Why do we need Xamarin Profiler you asked? 😮

slide21

As Mobile Developers we need to make sure we deliver a beautiful pixel perfect design for our end users, and specially according to my UX lead he’s going to haunt me in my nightmares if I don’t deliver a pixel perfect UI implementation. 😀

So we always have to do the tiny changes in padding or the height or the width or may be a tiny hex value in the color and so on, whereas every time we do a change we need to recompile the project and run.

And then even if you get the app to run, you still have to go navigate to the page that you just made the changes to, which takes a lot of time.

Now I’m aware of the existence of Xamarin Forms Previewer, but if you had already tried it out, we are well aware there’s a whole bunch of bugs and issues with it when it comes to complex UI designs, which has a whole bunch of custom renderers.

So for a solution to all the above scenarios, Xamarin has given us this awesome tool, Xamarin Inspector! 😀

slide22

An awesome tool that allows you to debug and analyze or modify your application UI at run time without having to recompile your code. 😉

Something really cool about this tool is that it gives this awesome exploded 3D layers view of your application UI. Which makes it very easy to analyze the rendered layers and get rid of any extra layers to improve performance.

slide23

Xamarin Inspector has two main features, first is the REPL access. REPL stands for Read, Evaluate, Print and Loop, which allows you to inject code to your application in real time.

Then the Visual Inspector allows you to interact with your UI hierarchy in real time in an intuitive 3D view.

So that you could make necessary changes to your UI in real time and see it instantly rendered on your emulator. 😉

Something very important to keep in mind is that, with the latest update for this tool, they are providing you direct Xamarin Forms support, so no longer you have to deal with the native-rendered properties, you could easily make changes to your Xamarin Forms properties on the fly.

Conclusion

slide25

Yep that’s it fellas! now get out there and build something awesome with Xamarin! 😀

Cheers!

-Udara Alwis, out! 😛

So I played around with Xamarin Forms Control Templates!

Yes I did and I came up with something pretty cool. Do you want to change your app’s theme on demand at run time? or load a different template for your pages at run time? or even simply change the app’s colors on demand?

Oh yeah Xamarin Forms Control Template gives the answer to all of that! 😉 Here what I built with it! 😀

xf-control-templates-ios xf-control-templates-android

Pretty cool eh! 😀

So basically what I built was a simple app where you could dynamically change the App background  color theme and change the change the App theme style on demand.

As you can see you can change the color theme of the app by clicking on the color buttons and change the theme style by clicking on the theme change button, which loads a different theme for the App if you closely notice.

The honest inspiration for this is that I remember back in the days when I was installing Windows 8 in my laptop, at the first time boot up, they ask you to choose the color theme you would like to use.

installation-7

Where it presents you with a beautiful color pallet and when you click on any of those colors the whole page changes the color accordingly, so I wanted to build something like that for the fun someday. 😉

So here we go… 😀

What are Xamarin Forms Control Templates?

Xamarin.Forms control templates provide the ability to easily theme and re-theme application pages at runtime. – Xamarin Docs 

Nuff said, if you want to learn more about it, read the documents. Here I’m going to explain how you could achieve the above cool stuff using Control Templates for Xamarin Forms.

Xamarin Forms Control Templates Binding?

I have used the Binding in order to change the template color at runtime. 🙂 If you’re not familiar with this concept, you may read up here: Xamarin Docs

We are keeping a public Property for the Theme color in our ContentPage, and binding our Control Template’s color values to that property. So at the run time whenever we change the Color property, it will get reflected to whatever the Template and the background color will change accordingly. 😉

Otherwise we would have to create different Control Templates for every single color, which will be very heavy and long code, but thanks to Binding we could do it with ease as described above.

Let me walk you through…

1. Creating templates…

First of all let’s create our templates, we are going to create two templates with different styles, as show in the below screenshots of the finished implementation.

simulator-screen-shot-1-jan-2017-2-53-32-pm  simulator-screen-shot-1-jan-2017-2-53-45-pm

  1. Template Header and footer will have a background and simple Label for both header and footer.
  2. Template Header will have one label with with a white background color, and footer will have two labels with white background color.

For now just forget about the color and we will focus on the initial Template Design.

Alright now let’s get to work.

Let’s begin by creating the project, and make sure to create XAML based Xamarin Forms project. Then let’s create our Control Templates in the App.xaml file, within the Application.Resources tag by adding them to the global ResourceDictionary, so that they could be accessed in anywhere of the app at runtime.

You can create any number of templates as you wish and name them in anyways you prefer. 😉 More themes the merrier…

<Application.Resources>
<ResourceDictionary>

  <!--template theme 1-->
  <ControlTemplate x:Key="MyTemplate1">
    ...
  </ControlTemplate>

  <!--template theme 2-->
  <ControlTemplate x:Key="MyTemplate2">
    ...
  </ControlTemplate>

</ResourceDictionary>
</Application.Resources>

 

le template 1…

Alright let’s create our first Control Template.

<!--template theme 1-->
<ControlTemplate x:Key="MyTemplate1">
<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="0.1*" />
    <RowDefinition Height="0.8*" />
    <RowDefinition Height="0.1*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="0.05*" />
    <ColumnDefinition Width="0.95*" />
  </Grid.ColumnDefinitions>

  <!--template header-->
  <!--use of template binding for color-->
  <BoxView Grid.ColumnSpan="2" Color="{TemplateBinding Parent.ThemeColor}" />
  <Label Grid.Row="0" Grid.Column="1"
         Text="this is my theme style 1"
         TextColor="White"
         VerticalOptions="Center" />
  <!--template header-->

  <!--your page content goes in here-->
  <ContentPresenter Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" />

  <!--template footer-->
  <!--use of template binding for color-->
  <BoxView Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Color="{TemplateBinding Parent.ThemeColor}" />
  <Label Grid.Row="2" Grid.Column="1"
         Text="template 1 (c) Udara Alwis 2016"
         TextColor="White"
         VerticalOptions="Center" />
  <!--template footer-->
</Grid>
</ControlTemplate>

 

There you have it, as you can see we have created a template with a Grid where we are aligning the page content in the middle  as the ContentPrensenter and the Header and Footer accordingly at top and bottom. We have added simple Labels to each Header and Footer with some text in it.

You can also notice that we are using Template property Binding to set the Background color of our Template. Color=”{TemplateBinding Parent.ThemeColor}”

So at the run time the Color will change according to the “ThemeColor” property which we will be implementing in the ContentPage.

You can use Binding to Change any property in your Control Templates thanks to awesomeness of Xamarin Forms! 😀

le template 2…

Now here’s our second Control Template.

<!--template theme 2-->
<ControlTemplate x:Key="MyTemplate2">
<Grid>
  <Grid.RowDefinitions>
	<RowDefinition Height="0.1*" />
	<RowDefinition Height="0.8*" />
	<RowDefinition Height="0.1*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
	<ColumnDefinition Width="0.05*" />
	<ColumnDefinition Width="0.35*" />
	<ColumnDefinition Width="0.55*" />
	<ColumnDefinition Width="0.05*" />
  </Grid.ColumnDefinitions>

  <!--template header-->
  <!--use of template binding for color-->
  <BoxView Grid.ColumnSpan="4" Color="{TemplateBinding Parent.ThemeColor}" />
  <Label Grid.Row="0" Grid.Column="1"  Grid.ColumnSpan="2"
		 Text="this is my theme style 2"
		 TextColor="Black"
		 BackgroundColor="White"
		 VerticalOptions="Center" />
  <!--template header-->

  <!--your page content goes in here-->
  <ContentPresenter Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="4" />

  <!--template footer-->
  <!--use of template binding for color-->
  <BoxView Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="4" Color="{TemplateBinding Parent.ThemeColor}" />
  <Label Grid.Row="2" Grid.Column="1"
		 Text="template 2"
		 TextColor="Black"
		 BackgroundColor="White"
		 VerticalOptions="Center" />
  <Label Grid.Row="2" Grid.Column="2"
		 Text="(c) Udara Alwis 2016"
		 TextColor="Black"
		 BackgroundColor="White"
		 VerticalOptions="Center"/>
  <!--template footer-->
</Grid>
</ControlTemplate>

 

As you can see the difference of this Template is that we have added extra columns to the Grid container and added extra labels to fill in. Also you may have noticed that we are setting the Label background to White color in this template.

Alright there goes our two templates in this example. Next let’s implement the design for our ContentPage.

2. ContentPage design stuff…

So those two Template themes are now ready to be applied for any ContentPage in our App.

Next let’s lay down the design for our content page. Remember hence we are using Control Templates, we need to implement our UI in a way our page could use those templates, which is by,

having a ContentView which will position itself in the ContentPresenter in the Templates once we bind to them.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:XFControlTemplateThemes"
             x:Class="WhateverYourNamespace.MainPage">

  <ContentView x:Name="contentView"
               ControlTemplate="{StaticResource MyTemplate1}">
    <ContentView.Padding>
      <OnPlatform x:TypeArguments="Thickness" iOS="0,20,0,0" />
    </ContentView.Padding>

   <!-- Your Page Content-->

  </ContentView>
</ContentPage>

 

You may have noticed that I have bound our ContentView ControlTemplate  property to one of the Templates we created in the App.xaml yeah? Yep exactly that’s because since we placed those templates in the App’s global level, we can directly access those properties from anywhere in our app. So as of the defualt ControlTemplate I have set it to the “MyTemplate1” template we created. So when the page loads it will be decorated with that. 😉

Now let’s take a look at the Page content design which will be placed inside the ContentView above. 🙂

Now keep in mind you can implement whatever the design you want to your Page body, but for this example basically we need to have a button to switch in between the two themes we created above and another bunch of buttons to change the color of those themes (something like a color pallet). So here we go…

<StackLayout VerticalOptions="CenterAndExpand" Padding="10,0,10,0">

  <Label Text="Welcome to the Dynamic Theme Changer app!"
		 HorizontalTextAlignment="Center"
		 FontSize="20"
		 VerticalOptions="Start"
		 HorizontalOptions="Center" />

  <Grid Padding="0,20,0,20">
	<Label Text="click below to change the theme on the go"
		   HorizontalTextAlignment="Center"
		   HorizontalOptions="Center" />
	<Button Text="change current theme template" Grid.Row="1"
				Clicked="OnButtonClicked" />

	<Grid.RowDefinitions>
	  <RowDefinition Height="*" ></RowDefinition>
	  <RowDefinition Height="40" ></RowDefinition>
	</Grid.RowDefinitions>
  </Grid>

  <Grid Padding="0,20,0,20">

	<Label Text="click below to change the theme color on the go"
		   HorizontalTextAlignment="Center"
		   HorizontalOptions="Center"
		   Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="10"/>

	<Button BackgroundColor="#ff0000" Grid.Row="1" Grid.Column="0" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#ff8000" Grid.Row="1" Grid.Column="1" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#ffff00" Grid.Row="1" Grid.Column="2" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#00ff40" Grid.Row="1" Grid.Column="3" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#00ffff" Grid.Row="1" Grid.Column="4" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#0080ff" Grid.Row="1" Grid.Column="5" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#4000ff" Grid.Row="1" Grid.Column="6" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#bf00ff" Grid.Row="1" Grid.Column="7" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#ff0080" Grid.Row="1" Grid.Column="8" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#ff0040" Grid.Row="1" Grid.Column="9" Clicked="OnColorChangeButtonClicked" />

	<Grid.RowDefinitions>
	  <RowDefinition Height="*" />
	  <RowDefinition Height="40" />
	</Grid.RowDefinitions>
	<Grid.ColumnDefinitions>
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	</Grid.ColumnDefinitions>
  </Grid>

</StackLayout>

 

Behold my beautiful UI. 😉 As you can see the first button will be switching in between the themes we created before, and them there’s a whole another set of buttons (color pallet buttons) with different background colors, which points to the same click event. Those buttons will be changing the template color by changing the ThemeColor property I mentioned earlier, which we are going to implement next. 🙂

3. ContentPage code-behind…

Now this is where we put things together, in your MainPage.cs code behind. Which we are handling all the theme changes and color changes on the go. 😉

So here are what we are going to implement here…

  1. ThemeColor public property to be used by the Templates for Color changing feature
  2. Load the control templates to be used in this page for run time theme changing
  3. Handle the run time theme switching functionality (switch the themes in between the templates we created before)
  4. Handle the tun time them color switching functionality (switch the themes between different color as show in those color buttons)
public partial class MainPage : ContentPage
{
	public static readonly BindableProperty ThemeColorProperty =
		BindableProperty.Create("ThemeColor", typeof(Color), typeof(MainPage), Color.Red);
	/// <summary>
	/// Gets or Sets the theme color for the template
	/// </summary>
	public Color ThemeColor
	{
		set { SetValue(ThemeColorProperty, value); }
		get { return (Color)GetValue(ThemeColorProperty); }
	}

	private bool _originalTemplate = true;
	private ControlTemplate _myTemplate1;
	private ControlTemplate _myTemplate2;

	public MainPage()
	{
		InitializeComponent();

		_myTemplate1 = (ControlTemplate)Application.Current.Resources["MyTemplate1"];
		_myTemplate2 = (ControlTemplate)Application.Current.Resources["MyTemplate2"];
	}

	void OnButtonClicked(object sender, EventArgs e)
	{
		// switching to the next theme
		_originalTemplate = !_originalTemplate;
		contentView.ControlTemplate = (_originalTemplate) ? _myTemplate1 : _myTemplate2;
	}

	private void OnColorChangeButtonClicked(object sender, EventArgs e)
	{
		if (((Button)sender) != null)
		{
			var sender1 = ((Button)sender);

			// Change the theme color according 
			// to the selected button color
			ThemeColor = sender1.BackgroundColor;

			// this will update the ThemeColor property
			// and reflect to the Control template
		}
	}
}

 

You can see I have implemented the ThemeColor property where our Templates will be binding their Color properties to. Then take a look at the event OnColorChangeButtonClicked which is the event that is fired by the set of buttons with different colors as we implemented in the UI. So inside this event we are retrieving the button’s background color and setting that value to our ThemeColor property, which will in return reflect to the Template that has been loaded to the page at that moment.

And then in the Constructor we are loading the two templates we created before into our page by accessing the Application Resources dictionary so we can use those instances to change the them on the go.

Inside the OnButtonClicked event we are switching between the two template themes we have loaded above.

Finally hit F5!

Alright that’s it for the coding. Now save it and hit F5 to see the magical beauty of Xamarin Forms! 😉

xf-control-templates-ios  xf-control-templates-android

So you can see clearly that when you click on the “change current theme template” button, the theme immediately changes to the next template.

And then you click on any of the color pallet buttons you can see the theme background color changes accordingly. Beautiful isn’t it? 😉

There you have it fellas!

Now as for them lazy people, you could straight away grab the code up in my github: Xamarin-Playground/XFControlTemplateThemes

Enjoy and share! 😀

– Udara Alwis

Is your Visual Studio stuck at, Emulator is already running?

So few days back after doing a fresh installation on my WIndows 10 laptop, and installing Visual Studio, I tried running a Xamarin Forms project, with the Visual Studio Android Emulator.

The project was successfully building itself, and the Visual Studio Android Emulator also started running successfully, but then the build process was on a hang state after the Emulator started running. Specifically the build log was on a hang state after “Emulator is already running” step, as I saw in the output log in VS.

So after Googling a while I figured out the problem thanks to wasting a bunch on hours on google search and forums, since many others were also having the same issue.

So let me post the solution for you right here.

Cause?

You must keep in mind that my project was building fine, and the Emulator also started running successfully and booted up itself. I was having a already built solution and up and running Emulator, but the VS couldn’t connect to the Emulator.

The cause for this is Visual Studio debugger was unable to connect to the started Emulator through the ADB (Android Debug Bridge).

This is due a wrong registry entry in the system, where as Visual Studio is looking to start up the ADB and connect to it, in order to connect to the Emulator, but due to this wrong registry entry, VS is unable to find the path to ADB, to start it up.

This is very well explained in this Visual Studio troubleshoot article:

https://msdn.microsoft.com/en-us/library/mt228282.aspx?f=255&MSPPError=-2147217396#ADB

This seem to be happening by default with fresh installations of VS lately, where as the Android SDK installation path in the above registry entry doesn’t seem to be matching with the actual SDK installation location in our system, which is probably done by default when installing Visual Studio 2015.

Solution!

So yeah as the article explains we just have to update the registry entry with the accurate path to the Android SDK installation in our system, so that Visual Studio can start up ADB to connect to the Emulator.

Step1 : Copy the actual Android SDK installation path

to find the actual Android SDK path in your system, that is referred by Visual Studio, go to the top tool bar of Visual Studio, and open the Android SDK Manager as shown below.

capture-3

If you did the default Visual Studio installation with the Cross-Platform mobile dev tools, then your path location should also look similar as above.

Copy that path, or type the same exact path on Run command and open the folder and copy the full path from there.

Step2 : Update the invalid registry entry

Open registry editor, by “regedit” in Run window and navigate to the following Registry.

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Android SDK Tools

Now open the Path registry key and change the value with the above Android SDK path which you copied earlier.

capture-2

Well, that’s it.

There goes the solution. Now you should close the Emulator and Visual Studio and reopen your solution, hit F5! you’re all good! 😀

Cheers!