Category Archives: Programming

Xamarin Forms cross platform architectural implementation patterns…

Let’s talk about how to properly handle advanced cross platform architectural implementations in Xamarin Forms projects, specifically when you’re abstracting native services/implementations in your shared code base, while trying to maintain loosely-coupled and scalable architecture.

Yaay! Xamarin Forms!

Now we all know how Xamarin Forms allows us to build cross platform mobile apps while sharing almost up to 100% of our code base and skill having native performance and look and feels.
It does this by adding a common layer of abstraction which shares properties and behaviors which are common for the native platforms.

BUT…

Despite the incredible architecture of the Framework, one of the main drawbacks of it is that we do not get access to 100% of the native properties and behaviors, thus we only get the “common subset” of behaviors of each native platform that are shareable in a common manner among all the platforms through Xamarin Forms.

OPS…

So when we need to access some properties, behaviors or services that’s not available from Xamarin Forms layer, we need to drill down to the native platform specific level of that certain platform.
Now for UI Controls and their properties or behaviors we could use Custom Renderes or Effects.

But how about inbuilt native Services, such as Storage, Text-to-Speech, Location and so on?

ABSTRACTION FTW!

Turns out it’s all abstraction of an interface and mapping it to a platform specific concrete implementation, which could be described as the famous “Bridge Pattern”.

A BUMMER..

Yes it does seem pretty simple but when it comes to actual practicality of it, then it becomes a little bit complicated or rather messy, unless you follow a proper implementation pattern.
And it only gets more complicated when you keep on scaling your app project.
Therefore it’s very crucial that we maintain a certain set of principal patterns when we do platform specific implementation with abstraction mapping.

THE SOLUTION?

So we need to make sure that we maintain a proper set of principal patterns when deal with this situation as I explained earlier.
Here I’m going to talk about three key principles to deal with advanced cross platform implementations for handling native abstractions.

  • Factory Pattern
  • Service Locator Pattern
  • Dependency Injection Pattern

Now with the above principle patterns you could maintain a properly constructed and easily scalable Xamarin Forms project solution, when you’re dealing with advanced cross platform implementations with abstracting native services. Or rather any kind of an abstraction service implementation you could keep properly maintained by following the above patterns. The key advantage in all the above patterns are decoupled code, and scalability at any given time.

Now keep in mind there’s actually many kinds of patterns you could follow in this scenario or you could come up with your own architectural patterns, but the above are known to be most used among Xamarin Forms projects.

It is best to be aware of them, since you could either use them straight away or modify them according to your requirements. And keep in mind the above principle patterns could become slightly changed from their literal definition when it comes to actual implementation, it’s only the foundation concept that we need to keep in mind when we implement them, and make sure we are following the basics of it at least.

Which one should I use?

There is no such thing as “the best” or “the worse”pattern for cross platform mobile development, it all depends on how you interpret it based on your requirements. The selection of which pattern or architecture suits best for you is totally up to you and your requirements, that is something very crucial to keep in mind. Therefore here in this post I shall be demonstrating each of the above patterns and how to implement them properly in a Xamarin Forms project solution for the same app concept.

Let’s talk Demonstration!

In order to properly demonstrate the above said patterns I will be implementing a simple Xamarin Forms app which allows you to writing notes, save them, view them, read them out loud, edit them, and also delete them. So in that case we will be using native Storage Services and Text-To-Speech Services of those native platforms, while having a shared code base.

Alright now, I’m not going to get into spoon feeding details of how to do each native services implementation such as Storage and Text-To-Speech and implementing the XAML pages for the app and so on, but I will only be focusing on implementing the pattern for the given scenario, which is what matters for this post.

So we are going to create a Xamarin Forms solution in Visual Studio, and keep the interface for the above native services in the PCL or Shared Project (INoteReader and INoteLoader) and have the concrete implementations of them to be moved down to the native projects.

Then to demonstrate the differences of implementation of all the above three patterns I have created a complete solution (XFCPMobilePatterns) which has three sub folders, and included three Xamarin Forms projects in each of them which has the demo for Factory Pattern (XFMyNotesAppFP), Service Locator Pattern (XFMyNotesAppSL) and Dependency Injection w/ IoC (XFMyNotesAppDI).

Yep, that’s how it would look, if you’re interested in diving further into the implementation, You may find the complete solution up on my Github repo: https://github.com/UdaraAlwis/XFCPMobilePatterns

Let’s begin.

1. FACTORY PATTERN with Xamarin Forms

Oh yeah, back to basics yeah? the good old Factory Pattern, which allows you to create objects without exposing the creation logic to the client, or as in without having to aware of the concrete implementation.

So for our implementation we are going to keep a static generic Factory which will handle mapping and creation of the services. And we would request the service by passing the service type.

public static class ServiceLoaderFactory<T>
{
    public static Func<T> CreateService { get; set; }
}

 

Alright next we are going to map our Service Interfaces (INoteReader and INoteLoader) which we have placed in the PCL project, with their actual concrete implementations in the platform specific projects using the ServiceLoaderFactory. Make sure to do this mapping in the run time execution point of each project as shown below.

// Android implementation
protected override void OnCreate(Bundle bundle)
{
	TabLayoutResource = Resource.Layout.Tabbar;
	ToolbarResource = Resource.Layout.Toolbar;

	base.OnCreate(bundle);

	global::Xamarin.Forms.Forms.Init(this, bundle);

	ServiceLoaderFactory<INoteLoader>.CreateService = () => new NoteLoaderDroid();
	ServiceLoaderFactory<INoteReader>.CreateService = () => new NoteReaderDroid();

	LoadApplication(new App());
}

// iOS implementation
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
	global::Xamarin.Forms.Forms.Init();
	LoadApplication(new App());

	ServiceLoaderFactory<INoteLoader>.CreateService = () => new NoteLoaderIos();
	ServiceLoaderFactory<INoteReader>.CreateService = () => new NoteReaderIos();

	return base.FinishedLaunching(app, options);
}

// UWP implementation
public App()
{
	ServiceLoaderFactory<INoteLoader>.CreateService = () => new NoteLoaderUwp();
	ServiceLoaderFactory<INoteReader>.CreateService = () => new NoteReaderUwp();

	this.InitializeComponent();
	this.Suspending += OnSuspending;
}

 

Next we need a NoteManager which is going to keep tract of all the service instances after they’re mapped to their concrete implementations at the run time, and also to maintain sort of a ‘facade-like’ access to the services. So for obvious reasons, we need to make it a singleton access point, as there’s no point of duplicating service objects. Also we are creating the NoteManager to handle basic functions such as loading and saving Notes at run time. 🙂

  public class NoteManager
  {
        // make a singleton access point
        private static readonly NoteManager _instance 
                                          = new NoteManager();
        public static NoteManager Instance 
                                  { get { return _instance; } }


        public IList<MyNote> MyNotes { get; private set; }


        public INoteLoader NoteLoader { get; private set; }
        
        public INoteReader NoteReader { get; private set; }

        private NoteManager()
        {
            NoteLoader = ServiceLoaderFactory<INoteLoader>.CreateService();
            NoteReader = ServiceLoaderFactory<INoteReader>.CreateService();

            MyNotes = new ObservableCollection<MyNote>(NoteLoader.Load());
        }

        public void Save()
        {
            NoteLoader.Save(MyNotes);
        }
  }

 

You can see there in the constructor, how we are loading the Service objects from our ServiceLoaderFactory and mapping them to the public interface instances, so that we could use them anywhere in our app.

Now the reason why I’m maintaining the NoteLoader and NoteReader instances here is because with the Factory Pattern, every time we request a service instance, it creates a new instance of the service and returns to the client, which obviously is not efficient, that’s why I’m retaining those instances in the NoteManager class. But with few tweaks you could easily implement a Factory Pattern which caches instances, and reuse them upon request, but I wouldn’t waste time on that, since we could use Service Locator or Dependency Injection for such scenarios, which I would explain later in the article.

Here’s how to access the above services in anywhere your PCL or Shared Project.

NoteManager.Instance.NoteReader.Speak("Hello, read this!");

 

There you have it, now that shows how to add platform dependent services and use them in your shared code following the Factory Pattern, as you go on scaling up the project solution! 😉

But keep in mind that this may not exactly according to literal definition of “Factory Pattern 101” but rather a customized version of it which I came up with for cross platform implementation, so you might have a different kind of implementation of the same concept, which is totally ‘ok’, as long as the foundation is the same. 🙂

2. SERVICE LOCATOR PATTERN with Xamarin Forms

As we already know, Service Locator Pattern, is all about locating a concrete implementation instance of an abstracted service interfaces at run time.
This is something similar to Factory Pattern, but a different type of a solution for our situation, whereas it maintains a dictionary of registered services which has been mapped with their concrete implementation, which we can look up at run time and retrieve the instance. Now it is considered that Service Locator pattern is a variation of Inversion of Control principle, just as Dependency Injection pattern, which we’ll discuss in the next topic.

This provides an on demand service look up at anywhere in the run time. The native service instances are stored in a dictionary-like data structure inside the Service Locator object, and returned at run time when they’re requested by the interface type. Obviously there will be a singleton static reference to the Service Locator object.

There’s many Service Locator ready-made libraries out there, and heck even Xamarin Forms already provides a solid Service Locator in the framework, which you may have already heard of, Xamarin Dependency Service. So you could use it right out of the box in Xamarin Forms, for your abstracted service implementations.

But that being said it’s not so hard to roll out our own Service Locator (just for the demonstration of it’s mechanics). 😉

So let’s implement our own simple Service Locator, this was actually something I grabbed off of github.

/// <summary>
///     Simple ServiceLocator implementation.
///     Extracted source credit : https://github.com/Azure-Samples/MyDriving/blob/master/src/MobileApps/MyDriving/MyDriving.Utils/ServiceLocator.cs
/// </summary>
public sealed class ServiceLocator
{
	static readonly Lazy<ServiceLocator> instance = new Lazy<ServiceLocator>(() => new ServiceLocator());
	readonly Dictionary<Type, Lazy<object>> registeredServices = new Dictionary<Type, Lazy<object>>();

	/// <summary>
	///     Singleton instance for default service locator
	/// </summary>
	public static ServiceLocator Instance => instance.Value;

	/// <summary>
	///     Add a new contract + service implementation
	/// </summary>
	/// <typeparam name="TContract">Contract type</typeparam>
	/// <typeparam name="TService">Service type</typeparam>
	public void Add<TContract, TService>() where TService : new()
	{
		registeredServices[typeof(TContract)] =
			new Lazy<object>(() => Activator.CreateInstance(typeof(TService)));
	}

	/// <summary>
	///     This resolves a service type and returns the implementation. Note that this
	///     assumes the key used to register the object is of the appropriate type or
	///     this method will throw an InvalidCastException!
	/// </summary>
	/// <typeparam name="T">Type to resolve</typeparam>
	/// <returns>Implementation</returns>
	public T Resolve<T>() where T : class
	{
		Lazy<object> service;
		if (registeredServices.TryGetValue(typeof(T), out service))
		{
			return (T)service.Value;
		}

		return null;
	}
}

 

As you can see how simple and straightforward it is. We maintain a singleton instance of the ServiceLocator, and there are the Add<TContract, TService>() which is used for registering the service interfaces with their concrete implementation and the Resolve<T>() which is used for retrieving the service instance at run time.

Notice how its maintaining a Dictionary of the service instances and retrieve it up on Resolve() call. 😉

Let’s add the above Service Locator to our project and construct it as below. And keep in mind the service implementation is going to be the same, having your service interfaces in the PCL shared project and the concrete implementations in the platform specific projects.

Now with our Service Locator this is how you would register your Service Interfaces (INoteReader and INoteLoader) with their concrete implementations.

// Android implementation
protected override void OnCreate(Bundle bundle)
{
	TabLayoutResource = Resource.Layout.Tabbar;
	ToolbarResource = Resource.Layout.Toolbar;

	base.OnCreate(bundle);

	global::Xamarin.Forms.Forms.Init(this, bundle);
	
	ServiceLocator.Instance.Add<INoteLoader, NoteLoaderDroid>();
	ServiceLocator.Instance.Add<INoteReader, NoteReaderDroid>();
	
	LoadApplication(new App());
}

// iOS implementation
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
	global::Xamarin.Forms.Forms.Init();

	ServiceLocator.Instance.Add<INoteLoader, NoteLoaderIos>();
	ServiceLocator.Instance.Add<INoteReader, NoteReaderIos>();

	LoadApplication(new App());

	return base.FinishedLaunching(app, options);
}

// UWP implementation
public App()
{
	ServiceLocator.Instance.Add<INoteLoader, NoteLoaderUwp>();
	ServiceLocator.Instance.Add<INoteReader, NoteReaderUwp>();

	this.InitializeComponent();
	this.Suspending += OnSuspending;
}

 

Then just like what we had in Factory Pattern implementation we need a NoteManager which is going to handle basic Note managing functions such as loading and saving notes. 🙂

public class NoteManager
{
	// make a singleton access point
	private static readonly NoteManager _instance 
                                          = new NoteManager();
	public static NoteManager Instance 
                                  { get { return _instance; } }


	public IList<MyNote> MyNotes { get; private set; }
	
	private NoteManager()
	{
		var noteLoader = ServiceLocator.Instance.Resolve<INoteLoader>();
		MyNotes = new ObservableCollection<MyNote>(noteLoader.Load());
	}

	public void Save()
	{
		var noteLoader = ServiceLocator.Instance.Resolve<INoteLoader>();
		noteLoader.Save(MyNotes);
	}
}

 

As you can see, compared to the NoteManager we had in the Factory Pattern, this NoteManager is much more simplified and cleaner thanks to the ServiceLocator.

This is because ServiceLocator allows us to maintain a single instance of our services such as INoteLoader and INoteReader, thereby we do not have to worry about duplicating their instances, we could simply access them anywhere in our code.

You can see how its easily calling the ServiceLocator.Resolve<T> to retrieve the service instances. 🙂

Here’s how to access the above services in anywhere your PCL or Shared Project, and notice how we are directly accessing the service instance unlike in Factory Pattern thanks to the ServiceLocator.

ServiceLocator.Instance.Resolve<INoteReader>().Speak("Hello, read this!");

 

There you have it, now this clearly shows how easy it is to add more and more platform dependent services and use them in your shared code as you go on scaling up the project solution, all thanks to Service Locator Pattern! 😉 Altogether while simplifying the shared code compared to the Factory Pattern.

And keep in mind this is a well improved pattern over Factory Pattern, but it still depends on your requirement as to which one is best suited for your implement. 🙂

3. DEPENDENCY INJECTION with Xamarin Forms

Now this right here is like the holy grail or the most praised and most used pattern in our scenario. Dependency Injection is all about injecting dependencies to create a given object just as said by its name. This is all about automatically resolving the required dependencies at run time without having the client specifically looking it up and creating them and injecting them to the new object to be created. So we are delegating the whole dependency resolving to an automated mechanism, thus a very popular form of Inversion of Control principle, whereas a massive improvement over the Service Locator.

Service Locator is good enough, only for smaller scale projects, where as you register services manually and look them up on demand at run time. But when the project gets more bigger and complex, with a lot of inter-connecting service and dependencies, it is very hard to keep a track on all of them, and most likely you’ll up missing a whole bunch of required dependencies in your code. This is usually a common case when you move into patterns such as MVVM implement for your mobile project, where you deliberately loosely couple all the layers of your app project, and you could easily end up missing dependencies.

This is where Dependency Injection comes for the rescue, where as we inject the required dependencies in the constructor or as properties and delegate that whole process to an automated mechanism, which we call the “Container“. So whenever we implement a DI it always comes with a static singleton Container which manages all the dependencies and resolve them automatically at run time, and we just have to register the dependency mapping only with the container.

Now there’s so many kinds of Dependency Injection Containers out there for you to choose from, given the popularity of this pattern. Unity, Ninject, AutoFac, TinyIoC and so on are some examples. It’s also pretty straight forward to roll out our own, but for this demo I would use an existing DI Container, Unity, quite a popular counterpart in this space.

Alright then, first of all let’s add the Unity library to our solution.

Make sure to select your PCL project and all the platform specific projects when you’re adding Unity from nuget.

Let’s make use of the Dependency Injection with our IoC Container as below. Now there’s nothing to be changed in how you implement your abstract interfaces in your PCL shared project and concrete implementations in the platform specific projects. 🙂

Let’s create a static reference for our container instance.

public partial class App : Application
{
	// static DI Container instance
	public static UnityContainer Container { get; set; }

	public App()
	{
		InitializeComponent();
		MainPage = new NavigationPage(
                                new XFMyNotesAppDI.NoteListPage());
	}
	
	...
}

 

Next here’s our NoteManager which is going to handle basic Note managing functions such as loading and saving notes. 🙂 You might see something different than what we had in Service Locator.

public class NoteManager
{
	private readonly INoteReader _noteReader;
	private readonly INoteLoader _noteLoader;

	public IList<MyNote> MyNotes { get; private set; }
	
	public NoteManager(INoteLoader noteLoader, 
                                    INoteReader noteReader)
	{
		_noteReader = noteReader;
		_noteLoader = noteLoader;
		
		MyNotes = new 
                  ObservableCollection<MyNote>(_noteLoader.Load());
	}

	public void Save()
	{
		_noteLoader.Save(MyNotes);
	}
}

 

As you can see we are passing in the INoteLoader and INoteReader services to the constructor of the NoteManager, this means that NoteManger cannot exist without those parameters services. So what happens here is that, when we request an instance of the NoteManager, the IoC Container (Unity Container) will resolve those depending services instances and inject them into the NoteManager, whilst creating the NoteManager.

Look how simple and clear the NoteManager is compared to our Service Locator and Factory Pattern principles.

Also you can see that we are no longer maintaining a singleton static reference to the NoteManager like how we did in Service Locator, because we could do the same thing directly using our IoC Container as shown below. 🙂

public App()
{
	InitializeComponent();

	// resolve the NoteManager instance
	App.Container.RegisterType<NoteManager>(
                        new ContainerControlledLifetimeManager());
					 
	MainPage = 
             new NavigationPage(newXFMyNotesAppDI.NoteListPage());
}

 

That’s how we are registering our NoteManager instance with the container, and we are instructing the container to retain a single instance of it by passing in the ContainerControlledLifetimeManager() type object to it. Also its good to keep in mind there are several object life time management types in Unity Container which you could play around with.

One of the coolest things about IoC containers is that we could instruct it to how we need a certain object or a type should be managed in the run time of the app. 😉 Oh yeah, cool indeed!

Now with our Unity Container this is how you would register your Service Interfaces (INoteReader and INoteLoader) with their concrete implementations on the platform specific level.

Also something to keep in mind is that we need to instantiate our UnityContainer instance here in the platform specific level where the execution begins. 🙂

// Android implementation
protected override void OnCreate(Bundle bundle)
{
	TabLayoutResource = Resource.Layout.Tabbar;
	ToolbarResource = Resource.Layout.Toolbar;

	base.OnCreate(bundle);

	global::Xamarin.Forms.Forms.Init(this, bundle);
	
	App.Container = new UnityContainer();
	App.Container.RegisterType<INoteLoader, NoteLoaderDroid>();
	App.Container.RegisterType<INoteReader, NoteReaderDroid>();

	LoadApplication(new App());
}

// iOS implementation
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
	global::Xamarin.Forms.Forms.Init();

	App.Container = new UnityContainer();
	App.Container.RegisterType<INoteLoader, NoteLoaderIos>();
	App.Container.RegisterType<INoteReader, NoteReaderIos>();

	LoadApplication(new App());

	return base.FinishedLaunching(app, options);
}

// UWP implementation
public App()
{
	XFMyNotesAppDI.App.Container = new UnityContainer();
	XFMyNotesAppDI.App.Container.RegisterType<INoteLoader, NoteLoaderUwp>();
	XFMyNotesAppDI.App.Container.RegisterType<INoteReader, NoteReaderUwp>();

	this.InitializeComponent();
	this.Suspending += OnSuspending;
}

 

Thanks to the IoC Container you could easily access the NoteManager anywhere in your code, which will give you access to the static retained instance.

NoteManager _noteManager = App.Container.Resolve<NoteManager>();

 

And of course the services as well.

App.Container.Resolve<INoteReader>().Speak("Hello, read this!");

 

There you have it, now this clearly shows how easy it is to add more and more platform dependent services and use them in your shared code as you go on scaling up the project solution, all thanks to Dependency Injection Pattern! 😉

Specially you noticed how it simplifies our shared code compared to the Service Locator pattern. Also its worth it to notice, how using an IoC Container brings many useful features to the table that you could use to improve your code.

So again, which one should I use?

Now that should have given you a very good comparison between the use of,

  • Factory Pattern
  • Service Locator Pattern
  • Dependency Injection Pattern

Each one of those patterns have their own advantages and disadvantages, yet you may have noted a general aspect improvement over each other such as Factory Pattern < Service Locator Pattern < Dependency Injection Pattern. Let’s break it down as below.

Considering some of the negative aspects of NoteManager implementation in each pattern,

in Factory Pattern we had,

  • Maintain static singleton access to NoteManager
  • Maintain static references to the INoteLoader and INoteReader service objects
  • Use NoteManager to access INoteLoader and INoteReader service objects
  • Resolve INoteLoader and INoteReader service objects manually

in Service Locator Pattern we had,

  • Maintain static singleton access to NoteManager
  • Resolve INoteLoader and INoteReader service objects manually

in Dependency Injection Pattern we had,

  • none of the above issues

So there you can clarify my claim of general improvements over each pattern, Factory Pattern < Service Locator Pattern < Dependency Injection Pattern.

Although that’s being said, the choice of Pattern to follow is totally up to you and your requirements. As an example something like Factory Pattern or Service Locator Pattern would be good enough for a small scale projects and Dependency Injection would be perfect for large scale projects with heavy MVVM based apps which uses a lot of service dependencies and so on.

Conclusion?

So I hope my demonstration of each of the patterns and how to implement them properly in a Xamarin Forms project solution for the same app concept, may have helped you in deciding which patterns to be used in any given scenario, which uses cross-platform dependencies.

Oh once again, You may find the complete solution up on my Github repo: https://github.com/UdaraAlwis/XFCPMobilePatterns

Go ahead and play around with the app and check out how each pattern is used in the MyNotes App scenario! 😉

Cheers everyone! 😀

Advanced decorating of Xamarin Forms Slider for Android…

Alright so today I’m gonna take you guys through a journey of decorating a Xamarin Forms Slider control in Android…

Well we all know how basic the default Slider control in Xamarin Forms, but worry not, there are plenty of ways to decorate it with awesome features,specifically for Xamarin Android! 😀

It all started a few weeks back when I was playing around with the Slider control to add  a whole bunch of complex visual features in one of my company apps.

Let’s get started…

Alright, first thing first, we need set up our Custom Slider control first and attach it’s Custom renderer in Android.

So here goes the Custom Slider control subclassing in Xamarin Forms project…

namespace WhateverYourNamespace
{
    public class CustomSlider : Slider
    {

    }
}

 

Next set up the Custom Slider Renderer in your Android project…

[assembly:ExportRenderer(typeof(CustomSlider), typeof(CustomSliderRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class CustomSliderRenderer : SliderRenderer
    {
        protected override void
                 OnElementChanged(ElementChangedEventArgs<Slider> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
		// All the customization will go here
            }
        }
    }
}

 

How would I consume this in XAML you ask? Just as another ordinary view… 😉

<StackLayout>

	<local:CustomSlider 
	HeightRequest="7" 
	WidthRequest="350" 
	HorizontalOptions="Center"
	Minimum="0" Maximum="100" />

</StackLayout>

 

Now keep in mind all the customization that we are doing later will be done within this custom renderer.

Something to keep in mind is that,

the Xamarin Forms Slider control’s Android run time native counterpart is the SeekBar…

So the more you aware of the SeekBar’s properties, the more customization you could play around with! 😉

Alright let’s start decorating… 😀

Decoration 1 : Change color theme!

Want to change the color theme of your Slider? Here we go…

Let’s see the code.

if (e.NewElement != null)
{
	// progressbar and progressbar background color
	Control.ProgressDrawable.SetColorFilter(
		new PorterDuffColorFilter(
		Xamarin.Forms.Color.FromHex("#ff0066").ToAndroid(),
		PorterDuff.Mode.SrcIn));
}

 

Use the ProgressDrawable Property and set the ColorFilter to it as you wish… 😉 which will set the color theme to your Progress Bar , Progress Thumb, and the background bar…

Decoration 2 : Change only the Slider’s Thumb Color?

How about changing just the Progress Thumb’s color? Yes you may…

Look at that funky looking Progress Thumb! 😉

Code?

if (e.NewElement != null)
{
	// Set Progress bar Thumb color
	Control.Thumb.SetColorFilter(
		Xamarin.Forms.Color.FromHex("#8000ff").ToAndroid(), 
		PorterDuff.Mode.SrcIn);
}

 

Android SeekBar (which is the native handler of Xamarin Forms Slider on Android) has the Thumb property which allows you to customize the appearance of the little thumbnail head of the Slider control as we have used above.

Next! 😀

Decoration 3 : Change progress background Color?

How about changing only the Progress Bar’s background color? As you can see below..

Look at the boring default progress bar’s background color vs the purple background color! 😉 pretty cool!

Here’s how you do it,

if (e.NewElement != null)
{
	//Set Background Progress bar color
	Control.ProgressBackgroundTintList 
           = ColorStateList.ValueOf(
            Xamarin.Forms.Color.FromHex("#8000ff").ToAndroid());
	Control.ProgressBackgroundTintMode
           = PorterDuff.Mode.SrcIn;
}

 

Use the ProgressBackground property to set the TintList and the TintMode! 🙂

TADAA!

Decoration 4 : How about adding a secondary progress indicator?

Now we all have seen secondary progress indicators in progress bars, specially in online video stream players… 🙂 example take the Youtube player! 😉 So have you ever wanted to add such a cool feature to your Xamarin Forms Slider in Android? Let me show you how its done… 😉

Look how cool that is yeah! 😉

Alright let’s get into coding…

Now in Android we have this built in property called SecondayProgress which allows you to set a secondary progress value to your Slider or Seekbar as of native Android handler.

if (e.NewElement != null)
{
	// secondary progress value in Xamarin Forms units
	int secondaryProgressValue = 50;
	
	// secondary progress value in 
	// Android native Seekbar units
	int secondaryProgressValueInAndroidUnits =
	(int)((secondaryProgressValue - 
			((CustomSlider)Element).Minimum) /
	(((CustomSlider)Element).Maximum -  
			 ((CustomSlider)Element).Minimum) * 1000.0);

	// set the secondary progress value
	Control.SecondaryProgress = 
	secondaryProgressValueInAndroidUnits;
}

 

There you go, you can see that we are setting the SecondaryProgress value, but also take a closer look at the calculation that we are doing before setting it.

Now Xamarin Forms Slider and Xamarin Android Seekbar which is the handler for the Slider control, uses different value types or unit types for setting the Progress and the Secondary Progress values in native level. If we want to set the value from Xamarin Forms value units then we need to convert that value to Android Seekbar’s native values which is exactly what we are doing at the calculation. So basically we are setting the Xamarin Forms unit value according to the native units to Seekbar control.

Oh if you want to set the Secondary Progress from Xamarin Forms level then you can easily create a property in the CustomSlider class and use it down here in your Custom Renderer class 🙂 Imagination is the limit! 😉

Decoration 5 : May be change the Color of secondary progress indicator?

How about we spice it up by changing the color a little of the secondary progress? 😉

Look at that!

Time for coding…

Android Seekbar has this property called SecondaryProgressTintList and SecondaryProgressTintMode which allows you to achieve the above results and set the secondary progress color as you wish…

if (e.NewElement != null)
{
	//Set Seconday Progress bar color
	Control.SecondaryProgressTintList = 
	      ColorStateList.ValueOf(
		Xamarin.Forms.Color.FromHex("#8000ff").ToAndroid());
	Control.SecondaryProgressTintMode = 
	      PorterDuff.Mode.SrcIn;

	// secondary progress value in Xamarin Forms units
	int secondaryProgressValue = 50;
	
	// secondary progress value in 
	// Android native Seekbar units
	int secondaryProgressValueInAndroidUnits =
	(int)((secondaryProgressValue - 
	((CustomSlider)Element).Minimum) /
	(((CustomSlider)Element).Maximum - 
	 ((CustomSlider)Element).Minimum) * 1000.0);

	// set the secondary progress value
	Control.SecondaryProgress = 
		secondaryProgressValueInAndroidUnits;
}

 

And hey of course don’t forget to set the SecondaryProgress value while you’re at it!

Decoration 6 : I would call it Funky delight!

Alright, now all that being said, how about blending some of those different colors adding some funky delight-ness to the Slider? 😉

Well what I mean is, let’s try adding different color’s to Thumb, Progress Bar, Progress Bar background and Secondary Progress Bar!

Too much funky? I thought so!

How about these??? 😉

I know, I love playing with colors being a Visual oriented developer! 😀 lol

Your imagination is the limit fellas!

Here’s how you play around with the colors…

if (e.NewElement != null)
{
	// Different colors for ProgressBar components
	// Set Primary Progress bar color
	Control.ProgressTintList = 
		ColorStateList.ValueOf(
		Xamarin.Forms.Color.FromHex("#6200ea").ToAndroid());
	Control.ProgressTintMode 
		= PorterDuff.Mode.SrcIn;

	//Set Seconday Progress bar color
	Control.SecondaryProgressTintList = 
		ColorStateList.ValueOf(
		Xamarin.Forms.Color.FromHex("#b388ff").ToAndroid());
	Control.SecondaryProgressTintMode 
		= PorterDuff.Mode.SrcIn;

	//Set Progress bar Background color
	Control.ProgressBackgroundTintList = 
		ColorStateList.ValueOf(
		Xamarin.Forms.Color.FromHex("#b39ddb").ToAndroid());
	Control.ProgressBackgroundTintMode 
		= PorterDuff.Mode.SrcIn;

	// Set Progress bar Thumb color
	Control.Thumb.SetColorFilter(
		Xamarin.Forms.Color.FromHex("#311b92").ToAndroid(),
		PorterDuff.Mode.SrcIn);
}

 

Decide your flavor of colors and go crazy fellas! 😉

Decoration 7 : Remove Thumb Header may be?

Absolutely, check this out…

It’s pretty simply actually, simply set a Tranparent ColorDrawable to the Thumb property.

if (e.NewElement != null)
{
	// Hide thumb
	Control.SetThumb(
		new ColorDrawable(Color.Transparent));
}

 

Woot!

Decoration 8 : Let’s kick it up a notch!

Let’s add some more vibrant and complex customization to our Slider for Android! 🙂

How about throwing in some cool gradient effects…

So to achieve that, we shall be using Android native Styling with Drawables such as Shape, Gradients and so on.

We will create a native android xml Style file in your Resources/Drawable folder with the name “custom_progressbar_style.xml”

Here’s what you’ll be placing inside of it…

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

  <item android:id="@android:id/background">
    <shape>
      <corners android:radius="15dip" />
      <gradient
       android:startColor="#d9d9d9"
       android:centerColor="#e6e6e6"
       android:endColor="#d9d9d9"
       android:centerY="0.50"
       android:angle="270" />
    </shape>
  </item>
  
  <item android:id="@android:id/secondaryProgress">
    <clip>
      <shape>
        <corners android:radius="15dip" />
        <gradient
             android:startColor="#e6b3e6"
             android:centerColor="#ffcce0"
             android:endColor="#e6b3e6"
             android:centerY="0.50"
             android:angle="270" />
      </shape>
    </clip>
  </item>
  
  <item android:id="@android:id/progress">
    <clip>
      <shape>
        <corners android:radius="15dip" />
        <gradient
         android:startColor="#ff0066"
         android:centerColor="#ff00ff"
         android:centerY="0.50"
         android:endColor="#cc0052"
         android:angle="270" />
      </shape>
    </clip>
  </item>
  
</layer-list>

 

So to explain the above a little bit, we have created a Style layer-list which assigns the given styling items to the specific id’s of the SeekBar native control, such as the background, secondaryprogress, progress as you have noticed. Those drawable objects will replace the default styles of those segments in the SeekBar with these defined drawable objects.

First we are using a Shape drawable to to the Background property, which creates a gradient layer with the given colors and angle for creating a gradient effect! Also we are setting a radius value to corner so that the corners will be curved nicely.

Next for the Progress and the SecondaryProgress properties we are creating a similar Shape gradient as before but we are clipping it according to the given values of each of them.

if (e.NewElement != null)
{
	// Set custom drawable resource
	Control.SetProgressDrawableTiled(
	Resources.GetDrawable(
	Resource.Drawable.custom_progressbar_style,
	(this.Context).Theme));

	// Hide thumb to make it look cool lol
	Control.SetThumb(new ColorDrawable(Color.Transparent));
}

 

There’s how you set it in the custom renderer level, simply call the SetProgressDrawableTiled() method by passing the custom style of what we created above.

Also I have disabled the Thumb, just to make it look cooler. Its up to you though.

If you want to do more extensible customization like above and may be preserve the Thumb view and style that as well? then refer to this stackoverflow article: http://stackoverflow.com/questions/16163215/android-styling-seek-bar

Additionally you could have bitmap images or nine patch images as drawables to styling and so may other stuff.

Now this is like the holy grail.. where as you can see with Android you get full flexibility for any kind of complex customization!

Its only limited by your imagination! 😉

WooT! 😀

Decoration 9 : Can I reduce the above overridden Height?

So you’re worried of the height after setting the custom styling drawables as above? simply reduce the HeightRequest value in your Xamarin Forms code for our custom Slider view.

Right after we set the Custom ProgressDrawable styles in the renderer level, it overrides the Height property of native SeekBar  that’s assigned from Xamarin Forms level for each of those sub-views (ProgressBar, SecondaryProgressBar and Background sub views), so they expands themselves to the fullest as possible with the new Drawable objects.

<local:CustomSlider HeightRequest="7" WidthRequest="350"  HorizontalOptions="Center"
        Minimum="0" Maximum="100" />

 

So the above should give you control over the Height issue!

Or else you could set the dip IntrinsicHeight values in your XML style drawables itself as well (something extra)! 😉

Decoration 9 : Can I  have the above cool-ness programmatically without resources?

So you don’t like to deal with Android Resources and creating the Style XMLs and stuff?

Oh sure, no worries! but you will have to do a little bit of work to get the above simple XML Styling into pure code generated objects!

Let me begin by giving credit to this example written in Java which I found while I was in the same situation: FlatUI/FlatSeekBar.cs

So let’s see how we could create Drawable Style objects in C# code!

Now keep in mind all the Drawable objects we used in our XML file “custom_progressbar_style.xml” has their own programmatical counterparts such as Shape, Gradient and Clip by the names as ShapeDrawable, GradientDrawable, and ClipDrawable and so on likewise.

So we can convert any given XML style to a C# generated style drawable. (any native Android developer should be well aware of this)

So let’s do something similar! 😉

So we are going to create our own Drawable objects and set them to the sub-views of our Slider control for Android, just like how we did with the XML styling, but this time programmatically. Here is how it will look like…

There you haveit, let’s see how we did this…

if (e.NewElement != null)
{
	// Setting drawable styling programatically

	// progress
	var progress = new PaintDrawable(Color.Red);
	progress.SetCornerRadius(
		(int)DpToPixels(this.Context, 10));
	progress.SetIntrinsicHeight(
		(int)DpToPixels(this.Context,10));
	var progressClip = 
		new ClipDrawable(progress, GravityFlags.Left,
		ClipDrawableOrientation.Horizontal);

	// secondary progress
	var secondary = new PaintDrawable(Color.Gray);
	secondary.SetCornerRadius(
		(int)DpToPixels(this.Context, 10));
	secondary.SetIntrinsicHeight(
		(int)DpToPixels(this.Context, 10));
	var secondaryProgressClip = 
		new ClipDrawable(secondary, GravityFlags.Left, 
		ClipDrawableOrientation.Horizontal);

	// background
	PaintDrawable background = new 
                 PaintDrawable(Color.LightGray);
	background.SetCornerRadius(
		(int)DpToPixels(this.Context, 10));
	background.SetIntrinsicHeight(
		(int)DpToPixels(this.Context, 10));

	// retrieve LayerDrawable reference of the SeekBar control
	LayerDrawable layeredDrawableReference 
		= (LayerDrawable)Control.ProgressDrawable;
		
	// apply our custom drawable objects to the 
	// given sub-views through their IDs
	layeredDrawableReference.
	    SetDrawableByLayerId(
		Android.Resource.Id.Background, background);
	layeredDrawableReference.
	    SetDrawableByLayerId(
		Android.Resource.Id.Progress, progressClip);
	layeredDrawableReference.
	    SetDrawableByLayerId(
		Android.Resource.Id.SecondaryProgress, 
                  secondaryProgressClip);
}

 

So basically we are creating our our Drawable objects programatically, in this case PainDrawable objects and giving them different styling values such as Radius, Clipping, IntrinsicHeight and so on.

And then at the end we are going to retrieve the references for the sub-views of our native SeekBar in Android which is the after-rendering counterpart of Xamarin Forms Slider as I mentioned at the beginning. This is going to be a LayerDrawable object, which is going to allow us to set our own custom Drawable objects to each drawable layer by their IDs.

As you can see we are calling the SetDrawableByLayerId() on our LayerDrawable object and passing in the each sub-view reference and custom drawable objects we want to set to them. 😀

Now keep this in mind, here you could have any kind of drawable objects to create your custom drawable styling just like you previously did with GradientDrawable in XML style, have the exact same beautiful visual result rendered programatically! 🙂

That’s it…

Well fellas that’s it for now, well at least that’s all I came across while I was playing around with my Custom Renderer for Xamarin Forms Slider on Android! 😀

Enjoy and share!

CHEERS!

Let’s Override Navigation Bar back button click in Xamarin Forms…

So you would like to override the Navigation Bar back button click event in your Xamarin Forms App? 😉 Yeah could be for a Sign up Page, Order Details Page, or any kind of a Page where you want to do some execution or confirmation before the user actually navigates back to the previous page in your app…

It’s BACKWARD navigation time…

Yes we are not talking about forward navigation here, but BACKWARD navigation! where the user clicks on the back button on the Navigation Bar, or the actual Back button in Android phones, where we need to have some validation before the user actually navigates…

Oh hello! Where do you think you’re going? Are you sure you want to go back?

:\

Do you want to save your changes before you go back?

Please complete the empty fields because you go back!

😮

Do you want to go back before you save your changes?

Please confirm you want to cancel your changes and go back…

😛

Blah blah…

Well you know the scenarios… 😉

ummhh… but in Xamarin Forms?

Yeah the question is can we actually implement this behavior in Xamarin Forms?

YES! you can, but…

well yes obviously you can override the OnBackPressed() method in ContentPage control, but…

it works only on Android and only for the physical back button…

not the Navigation Bar back button…

owwhh SNAP!

Yes fellas, if you want to achieve the above behavior in Xamarin Forms, you literally can not do it straight out of the box, because the override-able  OnBackPressed() method in ContentPage only gets fired on Android’s physical (or screen bottom) back button’s click. It does not work for the Navigation Bar’s back button click.

But I did it…

So here’s a sneak preview of the results of my implementation…

  

Now look at that awesomeness.. When the user clicks on the Navigation Bar’s back button, I’m popping up a confirmation dialog.. 🙂

Alright, how did I do this?

So in order to do this we need to drill down to the native level and handle these Navigation Bar back button click. Let me explain further….

Android

So after compilation the Navigation Bar that we call in Xamarin Forms, turns into the Action Bar for Android during run time. So in order to capture the back button click the Action Bar we need to override the OnOptionsItemSelected() in your MainActivity class, which allows us to capture the navigation bar’s back button click. Since Xamarin Forms runs on a single Activity overriding the above event on your parent Activity class is enough to get our job done. 😉

iOS

And for iOS , the Xamarin Forms’s Navigation Bar is mapped to the UINavigationBar in iOS run time. But unfortunately there’s no way to override the back button click on the default back button in the UINavigationBar, the only solution is to replace the default back button with a custom back button and do our necessary event subscriptions with it. We can replace the default back button with our custom back button at the ViewWillAppear() event call of the UIViewController, and set our custom back button to UILeftBarButtonItem property. 😀

Bridging between Native Xamarin and Xamarin Forms?

Yep just by native implementation is not enough since we need to get a call back to our Xamrin Forms PCL or Shared project level right? So for that we shall be using a simple Action event where we subscribe to in our Xamarin Forms code level, and do the necessary execution when the mentioned Action event gets fired from the native project levels. 😉

Simple as that! 😀

Alright! time for coding.. 😀

So first we need to create a Custom ContentPage to be used as our Page in our Xamarin Forms project, where as we could enable or disable the Nav bar Back button event overriding. And we shall name it as the “CoolContentPage” lol, well why not, it is indeed cool! 😉 lol

namespace WhateverYourNamespace
{
    public class CoolContentPage : ContentPage
    {
        /// <summary>
        /// Gets or Sets the Back button click overriden custom action
        /// </summary>
        public Action CustomBackButtonAction { get; set; }

        public static readonly BindableProperty EnableBackButtonOverrideProperty =
               BindableProperty.Create(
               nameof(EnableBackButtonOverride),
               typeof(bool),
               typeof(CoolContentPage),
               false);
			   
        /// <summary>
        /// Gets or Sets Custom Back button overriding state
        /// </summary>
        public bool EnableBackButtonOverride
        {
            get
            {
                return (bool)GetValue(EnableBackButtonOverrideProperty);
            }
            set
            {
                SetValue(EnableBackButtonOverrideProperty, value);
            }
        }
    }
}

 

So there we have created the Action event that we are going to subscribe to in our Xamarin Forms code level and to be invoked from Xamarin native project level.

You can also see that I’m using a bool property to enable or disable the overriding of the Back Button click event, so that we can decide whether to subscribe to the overriding event or not as a page property.

next Xamarin Android stuff…

So as I explained at the beginning we need to override the OnOptionsItemSelected() event in our MainActivity class in order to capture the nav bar back button click in Android for Xamarin Forms.

public override bool OnOptionsItemSelected(IMenuItem item)
{
	// check if the current item id 
	// is equals to the back button id
	if (item.ItemId == 16908332)
	{
	   // retrieve the current xamarin forms page instance
	   var currentpage = (CoolContentPage)
	   Xamarin.Forms.Application.
	   Current.MainPage.Navigation.
	   NavigationStack.LastOrDefault();

	   // check if the page has subscribed to 
	   // the custom back button event
	   if (currentpage?.CustomBackButtonAction != null)
	   {
		 // invoke the Custom back button action
		 currentpage?.CustomBackButtonAction.Invoke();
		 // and disable the default back button action
		 return false;
	   }

	   // if its not subscribed then go ahead 
	   // with the default back button action
	   return base.OnOptionsItemSelected(item);
	}
	else
	{
	   // since its not the back button 
	   //click, pass the event to the base
	   return base.OnOptionsItemSelected(item);
	}
}

public override void OnBackPressed()
{
	// this is not necessary, but in Android user 
	// has both Nav bar back button and
	// physical back button its safe 
	// to cover the both events

	// retrieve the current xamarin forms page instance
	var currentpage = (CoolContentPage)
	Xamarin.Forms.Application.
	Current.MainPage.Navigation.
	NavigationStack.LastOrDefault();

	// check if the page has subscribed to 
	// the custom back button event
	if (currentpage?.CustomBackButtonAction != null)
	{
		currentpage?.CustomBackButtonAction.Invoke();
	}
	else
	{
		base.OnBackPressed();
	}
}

 

phewww… that was some long code snippet yeah! fear not child! let me explain…

So as I mentioned before when the user clicks on anything on the default Android navigation bar the above OnOptionsItemSelected() gets fired, where as we will check the clicked item’s id and check for the back button’s default id. Yes the default back button id is the same 16908332 integer in Xamarin Forms – Android applications.

There we will get an instance of the current Xamarin Forms page in the Navigation stack and look if the page has been subscribed to the Custom Back button click event, if so there we will invoke our CustomBackButtonAction, and disable the default click event. If the page hasn’t subscribed to the Action, then we shall pass the click event to the base allowing the default back stack navigation. 🙂 Simple as that! 😀

Now you may see that I have also overridden the OnBackPressed event as well. This is really not necessary if you don’t want to but as a good practice it’s better to override both Nav bar back button and physical back button click events at the same time.

then Xamarin iOS stuff…

Here comes the iOS implementation where we are going to replace the custom Navigation Bar back button and use our own Custom button for the back button as I explained at the beginning. 😀

Now I know when we are to replace the Back button of iOS, we need to replace it with the same similar looking back button, although its custom. This is not really an easy task, because we need to construct the identical back button from the scratch, including the image, fonts and inset values and so on. I have written a complete blog post about this in one of my previous posts. If you want you could refer to it as for the complete explanation here : Creating an identical Custom Navigation Bar Back Button in Xamarin iOS…

But for the sake of this post, I shall post the whole implementation here, but I shall not drill down to detailed explanation. 🙂 You can always prefer to the original post up there.. 😉

Now keep in mind for iOS you need to override the ViewWillAppear() method in your CoolContentPageRenderer class.

So the below code should be placed inside your CoolContentPageRenderer class…

public override void ViewWillAppear(bool animated)
{
     base.ViewWillAppear(animated);
     
     if (((CoolContentPage)Element).EnableBackButtonOverride)
     {
          SetCustomBackButton();
     }
}

private void SetCustomBackButton()
{
     // Load the Back arrow Image
     var backBtnImage = 
     UIImage.FromBundle("iosbackarrow.png");

     backBtnImage = 
     backBtnImage.ImageWithRenderingMode
     (UIImageRenderingMode.AlwaysTemplate);

     // Create our Button and set Edge 
     // Insets for Title and Image
     var backBtn = new UIButton(UIButtonType.Custom)
     {
          HorizontalAlignment =   
          UIControlContentHorizontalAlignment.Left,
          TitleEdgeInsets = 
          new UIEdgeInsets(11.5f, 15f, 10f, 0f),
          ImageEdgeInsets = 
          new UIEdgeInsets(1f, 8f, 0f, 0f)
     };

     // Set the styling for Title
     // You could set any Text as you wish here
     backBtn.SetTitle("Back", UIControlState.Normal);
     // use the white color in ios back button text
     backBtn.SetTitleColor(UIColor.White,
     UIControlState.Normal); 
     backBtn.SetTitleColor(UIColor.LightGray, 
     UIControlState.Highlighted);
     backBtn.Font = UIFont.FromName("HelveticaNeue",
     (nfloat)17);

     // Set the Image to the button
     backBtn.SetImage(backBtnImage, UIControlState.Normal);

     // Allow the button to Size itself
     backBtn.SizeToFit();

     // Add the Custom Click event you would like to 
     // execute upon the Back button click
     backBtn.TouchDown += (sender, e) =>
     {
          // Whatever your custom back button click handling
          if(((CoolContentPage)Element)?.
          CustomBackButtonAction != null)
          {    
            ((CoolContentPage)Element)?.
               CustomBackButtonAction.Invoke();
          }
     };

     //Set the frame of the button
     backBtn.Frame = new CGRect(
          0,
          0,
          UIScreen.MainScreen.Bounds.Width / 4,
          NavigationController.NavigationBar.Frame.Height);

     // Add our button to a container
     var btnContainer = new UIView(
     new CGRect(0, 0, 
     backBtn.Frame.Width, backBtn.Frame.Height));
     btnContainer.AddSubview(backBtn);

     // A dummy button item to push our custom  back button to
     // the edge of screen (sort of a hack)
     var fixedSpace = 
     new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace)
     {
          Width = -16f
     };
     // wrap our custom back button with a UIBarButtonItem
     var backButtonItem = new UIBarButtonItem("",
     UIBarButtonItemStyle.Plain, null)
     {
          CustomView = backBtn
     };

     // Add it to the ViewController
     NavigationController.TopViewController.
     NavigationItem.LeftBarButtonItems 
     = new[] { fixedSpace, backButtonItem };
}

 

Alright there you have it, now keep in mind you need to attach the iosbackarrow.png image to your Xamarin Forms solution’s iOS project’s Resources folder. 😉

As I mentioned above I will not be getting down to the details of the above implementation, but I will explain the nuts and bolts related to this post.

So if you notice above we are creating a custom button and we are subscribing to the TouchDown event of it, which is where we are going to check if the current page has subscribed to the CustomBackButtonAction event or not and proceed with the custom action or default back stack navigation event… 😀

Simple as that! 😉

How to use it, you asked?

Alright let’s consume this beautiful implementation! 😉

So here I’m using our CoolContentPage as a XAML page in my Xamarin Forms solution.

<WhateverYourNamespace:CoolContentPage 
 xmlns="http://xamarin.com/schemas/2014/forms"
 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
 xmlns:WhateverYourNamespace=
 "clrnamespace:XFNavBarBackBtnClickOverride;
 assembly=XFNavBarBackBtnClickOverride"
 x:Class="XFNavBarBackBtnClickOverride.Page2"             
 Title="Page 3"
 EnableBackButtonOverride="True"
 BackgroundColor="#00bfff">
  <StackLayout
    Spacing="20"
    Padding="20,10,20,10"
    VerticalOptions="Center"
    HorizontalOptions="Center" >

    <Label Text="This is the cool page, 
	which has the Navigation Bar Back button 
	click overriden. How go ahead and click that Back     
        button! ;)"
           FontSize="20"
           HorizontalTextAlignment="Center"
           TextColor="White"/>
    
  </StackLayout>
</WhateverYourNamespace:CoolContentPage>

 

You can notice that I’m setting the EnableBackButtonOverride=”True” property for enabling the overriding of the nav bar custom back button click.

So here’s in the code behind we are subscribing to the CustomBackButtonAction with our Alert dialog asking a verification if the user is sure that they want to go back.

namespace WhateverYourNamespace
{
    public partial class Page2 : CoolContentPage
    {
        public Page2()
        {
            InitializeComponent();
            
            if (EnableBackButtonOverride)
            {
                this.CustomBackButtonAction = async () =>
                {
                    var result = await this.DisplayAlert(null,
                        "Hey wait now! are you sure " +
                        "you want to go back?",
                        "Yes go back", "Nope");

                    if (result)
                    {
                        await Navigation.PopAsync(true);
                    }
                };
            }
        }
    }
}

 

Pay good attention here where if the user confirms they want to go back, then we will manually Pop the page by calling  Navigation.PopAsync() method. If not the back button click event will be ignored thanks to our custom back button click event overriding implementation. 😀

Now keep in mind, subscribing to the Action can be done in many other different ways, code-behind may not be the best practice if you’re heavy MVVM minded, where as may be you could move the custom Action event subscription to the CoolContentPage’s OnAppearing event or base class. All up to your preferences… 😉

Alright, let’s fire it up!

Oh child, just hit that F5! 😉

  

Look at that beauty! 😀 Well the colors and stylings I added myself though.. 😉

So you may grab the code up in my Github: Xamarin-Playground/XFNavBarBackBtnClickOverride

There you go fellas!

Happy coding and share the love! 😀

Udara Alwis out!

Creating an identical Custom Navigation Bar Back Button in Xamarin iOS…

Now there comes a time when the Developer has to override or customize the Back Button in their Xamarin iOS app. Well I’ve been there, hence let me share my experience…

Now the origin of my experience is that, I wanted to override the Back button click event of my Xamarin iOS, but since there’s no way to actually “override” the back button event, I had to completely get rid of the default back button and implement my own custom back button, but it had to be exactly similar as the original iOS back button…

45ffk

So let me ask you…

Have you ever wanted to override your Navigation Bar Back button in iOS  with Xamarin? or specially override it with an identical or similar looking custom button? may be to gain control of the Back button click event?

Then this post is for you… 😀

tumblr_inline_nl7ryzqono1rkrh6k

Custom, but Similar to the actual Back Button…

Yes that’s right, let me highlight the identical or similar looking custom back button, because it’s pretty simple and straightforward to override or replace the back button, but its a bit of struggle when you want to implement a custom back button which looks identical or similar to the original back button in iOS.

The key…

So the key things to keep in mind is that,

  • We need use an Image with a “Back Arrow” that is similar from look and size of the original back button.
  • Use similar Font size to display the Text
  • Use necessary padding and x/y values to place the Image and Text Title properly

Alright, let’s get into it…

Image with Back Arrow…

Now to find the image for the Back Arrow just google “iphone back button png” or something similar, you could easily find lots, I would recommend to use the icons8 website, which is where I got mine, https://icons8.com/web-app/15157/back

Make sure there’s no padding between the Image pixel space and the borders, in my case the image was 24×41 size

screen-shot-2017-03-02-at-1-09-15-pm

Oh another thing, make sure the Image is PNG, White color with a transparent back ground, so that you can edit the Tint as you go later if needed… 🙂

Title Text Font…

So for this one, I had to do a bit of playing around, which I found that “HelveticaNeue” and Font Size 17 is perfect for this. 🙂

Time for the coding… 😉

So let’s start off with loading the UIImage and initializing our UIButton.

// Load the Back arrow Image
var backBtnImage = UIImage.FromBundle("iosbackarrow.png");

backBtnImage = 
	backBtnImage.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);

// Create our Button and set Edge Insets for Title and Image
var backBtn = new UIButton(UIButtonType.Custom)
{
	HorizontalAlignment = UIControlContentHorizontalAlignment.Left,
	TitleEdgeInsets = new UIEdgeInsets(11.5f, 15f, 10f, 0f),
	ImageEdgeInsets = new UIEdgeInsets(1f, 8f, 0f, 0f)
};

 

And set up the necessary Edge Insets for the button Title and Image as shown above. Well those values I figured out by playing around with the positioning values for hours.. 😛 lol

Next let’s dive into the Button’s customization…

// Set the styling for Title
// You could set any Text as you wish here
backBtn.SetTitle("Back", UIControlState.Normal);
// use the default blue color in ios back button text
backBtn.SetTitleColor(UIColor.FromRGB(0, 129, 249), UIControlState.Normal); 
backBtn.SetTitleColor(UIColor.LightGray, UIControlState.Highlighted);
backBtn.Font = UIFont.FromName("HelveticaNeue", (nfloat)17);

// Set the Image to the button
backBtn.SetImage(backBtnImage, UIControlState.Normal);

// Allow the button to Size itself
backBtn.SizeToFit();

 

Alright, that’s quite a bit of code to swallow, so first we set the Title Text of the button, and keep in mind you could set any Text as you wish there, for now I’m just using “Back” text.. 🙂

Next for the Text Color in the Normal state, I have used the default Blue color variation that iOS use by default, you could also use any color you prefer as well 🙂 Next we set the Highlight state of Text to Light Gray.

As we discussed at the beginning we will use HelveticaNeue with Font size of 17 for the Title Text. And finally set the Image to the Button and allow it to fit to the required size. 😀

// Add the Custom Click event you would like to 
// execute upon the Back button click
backBtn.TouchDown += (sender, e) =>
{
	// Whatever your custom back button click handling
};

 

Now here’s something very important, we need to make sure we handle our custom back button click as shown above… 😉

So next we shall do the preparation for the Frame.

//Set the frame of the button
backBtn.Frame = new CGRect(
	0,
	0,
	UIScreen.MainScreen.Bounds.Width / 4,
	NavigationController.NavigationBar.Frame.Height);

// Add our button to a container
var btnContainer = new UIView(
	new CGRect(0, 0, backBtn.Frame.Width, backBtn.Frame.Height));
btnContainer.AddSubview(backBtn);

 

So there we are adding the Frame values to our Button, where as I’m setting the width to a quarter of the Screen width, and as of the Height, I’m retrieving the NavigationBar’s height for it.

Next we need to add our UIButton to a UIView container as show above and make sure it has the same Height and Width as our UIButton.

Time to wrap things up fellas…

// A dummy button item to push our custom  back button to
// the edge of screen (sort of a hack)
var fixedSpace = new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace)
{
	Width = -16f
};
// wrap our custom back button with a UIBarButtonItem
var backButtonItem = new UIBarButtonItem("", UIBarButtonItemStyle.Plain, null)
{
	CustomView = backBtn
};

// Add it to the ViewController
NavigationController.TopViewController.NavigationItem.LeftBarButtonItems 
= new[] { fixedSpace, backButtonItem };

 

So here’s the final steps, we are wrapping our button’s uiview container inside the UIBarButtonItem by setting it to the CustomView property. And then add it to the LeftBarButtonItems , which overrides the default existing Back Button.

Now you may wonder why there’s another UIBarButtonItem with the Width set to -16 value, this is actually to forcefully push our custom back button to the edge of the Navigation Bar. 😀 So that right, it is more of a hack to get the job done… 😉

See it in action…

So here’s our Custom iOS Back Button in action… 😀

screen-shot-2017-03-02-at-12-16-10-pm

Just for the sake of comparing here’s the default system Back Button in iOS…

screen-shot-2017-03-02-at-12-15-54-pm

Looks almost identical yeah! 😀

Well, that’s it fellas!

Enjoy! 😀

PS: I may have gotten some help from these posts on StackOverflow:

http://stackoverflow.com/questions/18384488/ios-7-uibarbutton-back-button-arrow-color
http://stackoverflow.com/questions/227078/creating-a-left-arrow-button-like-uinavigationbars-back-style-on-a-uitoolba

FormsAppCompatActivity is not calling OnOptionsItemSelected Xamarin Android…

So have you Sub-classed your MainActivity from FormsAppCompatActivity which is also the default Parent Class for MainActivity in Xamarin Forms Android project? but you can’t get a hit on the OnOptionsItemSelected override?

Welcome to another flash post!

Recently I tried..

So recently I tried to override the navigation bar Back button click on Android in one of my Xamarin Forms applications.

but Unfortunately…

So one way to handle this is by overriding the OnOptionsItemSelected method in MainActivity, which is the Single Activity that all our Xamarin Forms Views get’s laid upon. But unfortunately I wasn’t able to get a hit on the above override method.

then I noticed…

So this project solution was created on Visual Studio with Xamarin version 4.2.2.11, where as I noticed that the MainActivity was sub-classing from the FormsAppCompactActivity instead of good old FormsApplicationActivity which was the previous parent class for MainActivity.

No sense…

Since it did not make sense I turned to the Xamarin Forums, and lucky enough I found this thread, where few others were also experiencing the same issue.

https://forums.xamarin.com/discussion/comment/218663#Comment_218663

Reason? Probably…

So according to the forums, it appears to be some missing bug in Xamarin Android version, where as the Android Toolbar doesn’t get referenced to the Activity. Where as since we are using FormsAppCompactActivity as the base, the Toolbar in action is the Android.Support.V7.Widget.Toolbar, not the good old Android.Widget.Toolbar, which for some reason doesn’t get attached to the Activity.

Solution…

Well if you had gone through the above forum you may have found the solution already… Basically we just need to set the Action Bar reference in the Activity in your OnCreate() method.. 😉

Android.Support.V7.Widget.Toolbar toolbar 
	= this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);

 

or if I’m to share my MainActivity…

public class MainActivity : FormsAppCompatActivity
{
	protected override void OnCreate(Bundle bundle)
	{
		TabLayoutResource = Resource.Layout.Tabbar;
		ToolbarResource = Resource.Layout.Toolbar;

		base.OnCreate(bundle);

		global::Xamarin.Forms.Forms.Init(this, bundle);
		LoadApplication(new App());
		
		Android.Support.V7.Widget.Toolbar toolbar 
			= this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
		SetSupportActionBar(toolbar);
	}
}

 

Well there you have it! Solved! 😀

Cheers!

Le silly meaningless random string generator…

So here’s something I put together quickly by grabbing from stackoverflow, to generate some meaningless random string based on a given length of letters. 😀 This is actually a simple dot net implementation where as you could use it as a static class and use it anywhere you want. may be? up to you!

Here it is!

namespace WhateverYourNamespace
{
    public static class RandomWordGenerator
    {
        /// <summary>
        /// Just to generate some random words! 😛
        /// </summary>
        /// <param name="requestedLength"></param>
        /// <returns></returns>
        public static string GetMeaninglessRandomString(int requestedLength)
        {
            Random rnd = new Random();
            string[] consonants = { "b", "c", "d", "f", "g", "h", "j", "k",
                "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z" };
            string[] vowels = { "a", "e", "i", "o", "u" };

            string word = "";

            if (requestedLength == 1)
            {
                word = GetRandomLetter(rnd, vowels);
            }
            else
            {
                for (int i = 0; i < requestedLength; i += 2)
                {
                    word += GetRandomLetter(rnd, consonants) + 
                        GetRandomLetter(rnd, vowels);
                }

                word = word.Replace("q", "qu").Substring(0, requestedLength);
                // We may generate a string longer than requested length, 
                // but it doesn't matter if cut off the excess.
            }

            return word;
        }

        private static string GetRandomLetter(Random rnd, string[] letters)
        {
            return letters[rnd.Next(0, letters.Length - 1)];
        }
    }
}

 

Now I don’t own this original implementation, I just put it into a static class and used in one of my apps. Sorry I don’t have the actual source of it. 😦 but I do recall I grab it from stackoverflow.

Anyways use it as you wish.

KTHANKSBYE!

lol

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

Setting RelativeLayout ConstraintExpressions from XAML Styles in Xamarin Forms…

When it comes to Xamarin Forms RelativeLayout we always use Constraints, its pretty easy to add those Constraint values from C# code behind, but when it comes to XAML UI implementation, it’s not so easy.

so myself…

I have been working with XAML UI implementation for the last year or so, specially dealing with a lot of pixel perfect design, which needs a lot of customization to design from XAML. But as a developer you have to find ways to deal with those stuff. In my current project we practice a strict discipline of MVVM pattern, which we strongly separate XAML UI View and the ViewModel code. So under no exceptions we add any single C# UI code or XAML code behind implementations in our project.

complex design implementations…

When you have to deal with complex design implementations in Xamarin Forms, the best way to go is with RelativeLayout, along with Relative Constraint values for X/Y position and Height/Width values.

flag1

RelativeLayout is good…

Usually those RelativeLayout Constraint values manages to get the job done, with ease on both Android and iOS devices. But sometimes it doesn’t quite go right, specially with Android, where you have to deal with different types of screen resolutions.

layouts1

but sometimes…

So at times like that you need to specify RelativeLayout ConstraintExpression separately for iOS and Android devices. But how do you do this in XAML code?

so how?

So how do you set those ConstraintExpression right from XAML code? Styles is the answer! 😀

The trick is to create two different Styles for Android and iOS, targeting the control you need to set the RelativeLayout Constraints on.

And then on your control’s XAML declaration, you set the Style property using the OnPlatform tag accordingly for iOS and Android.

Let’s do it…

You could define these Styles on your Page level or Application level as you wish as shown below…

You can see I have created twp styles which targets the Label control type and added my Relative Layout ConstraintExpressions. 🙂 Also I have added the other Properties that I need to customize through these Styles.

<ContentPage.Resources>
	<ResourceDictionary>
		<Style x:Key="MyLabelStyleiOS" TargetType="Label">
		  <Setter Property="BackgroundColor" Value="Yellow"/>
		  <Setter Property="HorizontalTextAlignment" Value="Center"/>
		  <Setter Property="RelativeLayout.YConstraint" 
				  Value="{ConstraintExpression RelativeToParent,Property=Height,Factor=0.5}"/>
		  <Setter Property="RelativeLayout.WidthConstraint"
				  Value="{ConstraintExpression RelativeToParent,Property=Width,Factor=0.7}"/>
		  <Setter Property="RelativeLayout.XConstraint"
				  Value="{ConstraintExpression RelativeToParent,Property=Width,Factor=0.15}"/>
		</Style>

		<Style x:Key="MyLabelStyleAndroid" TargetType="Label">     
		  <Setter Property="BackgroundColor" Value="Yellow"/>
		  <Setter Property="HorizontalTextAlignment" Value="Center"/>
		  <Setter Property="RelativeLayout.YConstraint"
				  Value="{ConstraintExpression RelativeToParent,Property=Height,Factor=0.1}"/>
		  <Setter Property="RelativeLayout.WidthConstraint"
				  Value="{ConstraintExpression RelativeToParent,Property=Width,Factor=0.7}"/>
		  <Setter Property="RelativeLayout.XConstraint"
				  Value="{ConstraintExpression RelativeToParent,Property=Width,Factor=0.15}"/>
		</Style>
	</ResourceDictionary>
</ContentPage.Resources>

 

And then on the your Control that you need to set those RelativeLayout Constraints…

<Label Text="Welcome to the app!"  >
	<Label.Style>
	  <OnPlatform x:TypeArguments="Style"
				  iOS="{StaticResource MyLabelStyleiOS}"
				  Android="{StaticResource MyLabelStyleAndroid}" />
	</Label.Style>
</Label>

 

You can see how I have nested down the Style property and added the specific style according to the Platform type.

It’s very important to notice that I have added those Styles as StaticResource this is because we need to set those RelativeLayout ConstraintExpressions before the run time, while the XAML are being parsed. 🙂 Once the XAML layout is parsed, we can not set the ConstraintExpressions, since it’s not going to be rendered.

make it pretty… Generalize!

Yep the above styles are ugly, so let’s generalize it and move the common properties and constraints to a general style as below, and derive our child styles.

<Style x:Key="MyLabelStyle" TargetType="Label">
  <Setter Property="BackgroundColor" Value="Yellow"/>
  <Setter Property="HorizontalTextAlignment" Value="Center"/>
  <Setter Property="RelativeLayout.WidthConstraint"
		  Value="{ConstraintExpression RelativeToParent,Property=Width,Factor=0.7}"/>
  <Setter Property="RelativeLayout.XConstraint"
		  Value="{ConstraintExpression RelativeToParent,Property=Width,Factor=0.15}"/>
</Style>

<Style x:Key="MyLabelStyleiOS" TargetType="Label" BasedOn="{StaticResource MyLabelStyle}">
  <Setter Property="RelativeLayout.YConstraint" 
		  Value="{ConstraintExpression RelativeToParent,Property=Height,Factor=0.5}"/>
</Style>

<Style x:Key="MyLabelStyleAndroid" TargetType="Label" BasedOn="{StaticResource MyLabelStyle}">
  <Setter Property="RelativeLayout.YConstraint"
		  Value="{ConstraintExpression RelativeToParent,Property=Height,Factor=0.1}"/>
</Style>

 

There we go! now that’s beautiful. Always keep in mind to generalize the common Style properties, and here in this case the common ConstraintExpression values. 🙂

Cheers! 😀

An improved ScrollView control for Xamarin Forms by me, myself and I…

Alright now when it comes to the default Xamarin Forms ScrollView, its pretty much generic and limited with the simple common attributes and behaviours, and it does not deliver any specific “cool” features with it.

What’s so cool about it?

So I thought of creating my own Custom ScrollView for Xamarin Forms using Custom Renderers, which would include the following awesome features,

Bouncy Effect – Yeah you gotta admit, the bounce effect of a native scrollview is pretty fun to play with, in a User’s perspective. So I thought of enabling this feature in my custom ScrollView even when the Child Element doesn’t exceeds the ScrollView boundaries… 😉
(PS: this effect is interpreted in native Android and iOS differently)

Disabling and Enabling Horizontal and Vertical Scroll Indicators – Now sometimes these scroll bar indicators are useful but there are times which we want to hide them, as it might look ugly on the UI in certain cases. So yeah let’s have some control over it shall we? 😀

Background Image – Of course who wouldn’t like a background Image on a Scroll view eh! 😉 Well to be specific we are going to add a Fixed Background Image for the ScrollView. And note that this background Image would be fixed, and will not be scrolling with the Content of the ScrollView. (I will do another post to enable that feature).

Yes behold, me, myself and I presenting the “BloopyScrollView” why the name “BloopyScrollView”? I don’t even know. lol 😛

Implementation

Alright let’s go ahead and create our Custom ScrollView Control in the PCL project. Along with the following properties, so that we could have direct control over the above said behaviours.

Alright now expect this to be longer, since I have added the properties as Bindable Properties, so you could use them in any MVVM scenario with ease. 😀

namespace WhateverYourNamespace
{
    public class BloopyScrollView : ScrollView
    {
        public static readonly BindableProperty IsHorizontalScrollbarEnabledProperty =
        BindableProperty.Create(
            nameof(IsHorizontalScrollbarEnabled),
            typeof(bool),
            typeof(BloopyScrollView),
            false,
            BindingMode.Default,
            null);
        /// <summary>
        /// Gets or sets the Horizontal scrollbar visibility
        /// </summary>
        public bool IsHorizontalScrollbarEnabled
        {
            get { return (bool)GetValue(IsHorizontalScrollbarEnabledProperty); }
            set { SetValue(IsHorizontalScrollbarEnabledProperty, value); }
        }


        public static readonly BindableProperty IsVerticalScrollbarEnabledProperty =
        BindableProperty.Create(
            nameof(IsVerticalScrollbarEnabled),
            typeof(bool),
            typeof(BloopyScrollView),
            false,
            BindingMode.Default,
            null);
        /// <summary>
        /// Gets or sets the Vertical scrollbar visibility
        /// </summary>
        public bool IsVerticalScrollbarEnabled
        {
            get { return (bool)GetValue(IsVerticalScrollbarEnabledProperty); }
            set { SetValue(IsVerticalScrollbarEnabledProperty, value); }
        }


        public static readonly BindableProperty IsNativeBouncyEffectEnabledProperty =
        BindableProperty.Create(
            nameof(IsNativeBouncyEffectEnabled),
            typeof(bool),
            typeof(BloopyScrollView),
            true,
            BindingMode.Default,
            null);
        /// <summary>
        /// Gets or sets the Native Bouncy effect status
        /// </summary>
        public bool IsNativeBouncyEffectEnabled
        {
            get { return (bool)GetValue(IsNativeBouncyEffectEnabledProperty); }
            set { SetValue(IsNativeBouncyEffectEnabledProperty, value); }
        }


        public static readonly BindableProperty BackgroundImageProperty =
        BindableProperty.Create(
            nameof(BackgroundImage),
            typeof(ImageSource),
            typeof(BloopyScrollView),
            null,
            BindingMode.Default,
            null);
        /// <summary>
        /// Gets or sets the Background Image of the ScrollView
        /// </summary>
        public ImageSource BackgroundImage
        {
            get { return (ImageSource)GetValue(BackgroundImageProperty); }
            set { SetValue(BackgroundImageProperty, value); }
        }
    }
}

 

There we go IsHorizontalScrollbarEnabled, IsVerticalScrollbarEnabled to disable/enable Horizonal and Vertical Scrollbars.

IsNativeBouncyEffectEnabled to control the Native Bouncy effect.

BackgroundImage to set the ImageSource for the ScrollView’s background Image. And make sure to provide a proper image for this hence we will be resizing the given image in our native renderer level to fit to the background of the ScrollView.(You will see in the next steps below)

Alright let’s head over to creating the Custom Renderers associated with our BloopyScrollView.

Something to keep in mind…

So if you’re a frequent reader of my blog, you may remember sometime ago I created an Extention class for handling Xamarin Forms Images in Native code level: https://theconfuzedsourcecode.wordpress.com/2016/12/12/an-awesome-image-helper-to-convert-xamarin-forms-imagesource-to-ios-uiimage-or-android-bitmap/

Why I’m bringing this up, is because we are going to be needing it for this project. You ask why? Because we need to convert the above BackgroundImage, which is of type Xamarin Forms ImageSource.

So we need to convert that ImageSource to native UIImage or Bitmap image respectively in our Custom renderer levels. 😉

So go ahead and grab that code real quick and add it to your Native Projects. 😀

iOS Implementation

Now let’s create the Custom Renderer for the Control in Xamarin.iOS project.

[assembly: ExportRenderer(typeof(BloopyScrollView), typeof(BloopyScrollViewRenderer))]
namespace WhateverYourNamespace.iOS
{
    public class BloopyScrollViewRenderer : ScrollViewRenderer
    {
        private UIImage _uiImageImageBackground;

        protected override async void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            this.ShowsVerticalScrollIndicator = ((BloopyScrollView)e.NewElement).IsVerticalScrollbarEnabled;
            this.ShowsHorizontalScrollIndicator = ((BloopyScrollView)e.NewElement).IsHorizontalScrollbarEnabled;

            if (e.NewElement != null)
            {
                if (((BloopyScrollView)e.NewElement).IsNativeBouncyEffectEnabled)
                {
                    this.Bounces = true;
                    this.AlwaysBounceVertical = true;
                }

                if (((BloopyScrollView)e.NewElement).BackgroundImage != null)
                {
                    // retrieving the UIImage Image from the ImageSource by converting
                    _uiImageImageBackground = await IosImageHelper.GetUIImageFromImageSourceAsync(((BloopyScrollView)e.NewElement).BackgroundImage);
                }

                ((BloopyScrollView)e.NewElement).PropertyChanged += OnPropertyChanged;
            }
        }

        private void OnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
        {
            if (propertyChangedEventArgs.PropertyName == BloopyScrollView.HeightProperty.PropertyName)
            {
                // check if the Width and Height are assigned
                if (((BloopyScrollView)sender).Width > 0 & ((BloopyScrollView)sender).Height > 0)
                {
                    // resize the UIImage to fit the current UIScrollView's width and height
                    _uiImageImageBackground = ResizeUIImage(_uiImageImageBackground, (float)((BloopyScrollView)sender).Width, (float)((BloopyScrollView)sender).Height);

                    // Set the background Image
                    this.BackgroundColor = UIColor.FromPatternImage(_uiImageImageBackground);
                }
            }
        }

        // We need to override this to have the background image to be fixed
        public override void Draw(CGRect rect)
        {
            base.Draw(rect);
        }

        // Resize the UIImage
        public UIImage ResizeUIImage(UIImage sourceImage, float widthToScale, float heightToScale)
        {
            var sourceSize = sourceImage.Size;
            var maxResizeFactor = Math.Max(widthToScale / sourceSize.Width, heightToScale / sourceSize.Height);
            if (maxResizeFactor > 1) return sourceImage;
            var width = maxResizeFactor * sourceSize.Width;
            var height = maxResizeFactor * sourceSize.Height;
            UIGraphics.BeginImageContext(new CGSize(width, height));
            sourceImage.Draw(new CGRect(0, 0, width, height));
            var resultImage = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();
            return resultImage;
        }
    }
}

 

Inside the method we are assigning the relevant properties of our BloopyScrollView to the native control properties.

The UIScrollView which is associated with the Xamarin Forms ScrollView has the following native properties:

  • ShowsVerticalScrollIndicator: Make the vertical scrollbar visible or hidden
  • ShowsHorizontalScrollIndicator: Make the horizontal scrollbar visible or hidden
  • Bounces: Always enable the native bounce effect on iOS UIScrollView
  • BackgroundColor: Allows to set the background color for the UIScrollView or set an Image as a pattern

Also you may have noted that we are converting our Image Source BackgroundImage to a UIImage using our extension.

And then when the Height and Width are set to the Control, we are resizing the Image to fit those properties and setting that as the Background of the UIScrollView through the UIColor.FromPatternImage() which allows us to set the image as a pattern throughout the canvas of the UIScrollView.

the strange tale of getting the UIScrollView’s Fixed background in Xamarin… :O

Notice that we are overriding the Draw(CGRect rect) method, this is to have the UIScroll Background Image to be fixed within the boundaries, and not to be spanned across the Content area.

Because usually if we set the BackgroundColor property, it will span across the Content area, but strangely if we override the Draw() method, BackgroundColor would only be contained within UIScrollView’s boundaries, without spanning across the Content area. This is something I figured out while playing around with the above implementation. 😀

Alright let’s jump into Android… 😀

Android Implementation

Now let’s create the Custom Renderer for the Control in Xamarin.Android project.

[assembly: ExportRenderer(typeof(BloopyScrollView), typeof(BloopyScrollViewRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class BloopyScrollViewRenderer : ScrollViewRenderer
    {
        private Bitmap _bitmapImageBackground;

        protected override async void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            this.VerticalScrollBarEnabled = ((BloopyScrollView)e.NewElement).IsVerticalScrollbarEnabled;
            this.HorizontalScrollBarEnabled = ((BloopyScrollView)e.NewElement).IsHorizontalScrollbarEnabled;

            if (((BloopyScrollView)e.NewElement).IsNativeBouncyEffectEnabled)
            {
                this.OverScrollMode = OverScrollMode.Always;
            }

            if (((BloopyScrollView) e.NewElement).BackgroundImage != null)
            {
                // retrieving the Bitmap Image from the ImageSource by converting
                _bitmapImageBackground = await AndroidImageHelper.GetBitmapFromImageSourceAsync(((BloopyScrollView)e.NewElement).BackgroundImage, this.Context);

                // resize the Bitmap to fit the current ScrollView's width and height
                var _resizedBitmapImageBackground = new BitmapDrawable(ResizeBitmap(_bitmapImageBackground, this.Width, this.Height));

                // Set the background Image
                this.Background = _resizedBitmapImageBackground;
            }
        }

        // Resize the Bitmap
        private Bitmap ResizeBitmap(Bitmap originalImage, int widthToScae, int heightToScale)
        {
            Bitmap resizedBitmap = Bitmap.CreateBitmap(widthToScae, heightToScale, Bitmap.Config.Argb8888);

            float originalWidth = originalImage.Width;
            float originalHeight = originalImage.Height;

            Canvas canvas = new Canvas(resizedBitmap);

            float scale = this.Width / originalWidth;

            float xTranslation = 0.0f;
            float yTranslation = (this.Height - originalHeight * scale) / 2.0f;

            Matrix transformation = new Matrix();
            transformation.PostTranslate(xTranslation, yTranslation);
            transformation.PreScale(scale, scale);

            Paint paint = new Paint();
            paint.FilterBitmap = true;

            canvas.DrawBitmap(originalImage, transformation, paint);

            return resizedBitmap;
        }
    }
}

 

The Android ScrollView which is associated with the Xamarin Forms ScrollView has the following native properties:

  • VerticalScrollBarEnabled: Make the vertical scrollbar visible or hidden
  • HorizontalScrollBarEnabled: Make the horizontal scrollbar visible or hidden
  • OverScrollMode: Always enable the native bounce effect on Android ScrollView
  • Background: Allows to set the background drawable for the ScrollView

As you may have noticed we are converting our Xamarin Forms Image Source BackgroundImage to a Bitmap image using our extension.

Then we are resizing out Bitmap image according to the Width and Height of the ScrollView to fit to the full background to be wrapped around a BitmapDrawable and set to the Background of ScrollView.

There you go! 😀

Let’s use it… 😉

Alright now that’s done, let’s consume this in our PCL project.

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

	<Label Text="Welcome to Xamarin Forms!"
		   VerticalOptions="Center"
		   HorizontalOptions="Center" />

	<local:BloopyScrollView 
	IsNativeBouncyEffectEnabled="True"
	IsVerticalScrollbarEnabled="False"
	IsHorizontalScrollbarEnabled="False">
	<local:BloopyScrollView.BackgroundImage>
	  <FileImageSource File="xamarinBackgroundImage.png"/>
	</local:BloopyScrollView.BackgroundImage>
	
			<Label
			  FontSize="22"
			  HeightRequest="400"
			  Text=
			  "Whatever your text content to be displayed." />
			  
	</local:BloopyScrollView>

</StackLayout>

 

As you can see I have inserted my BloopyScrollView in a StackLayout and as the content of the ScrollView I have added Label. Well you can add any content you want or set any Height or Width as you wish.

Notice that I have set IsNativeBouncyEffectEnabled to be True as I want to see the native Bouncy effect. Then I have disabled the Vertical and Horizontal Scrollbars from the properties we added earlier. Then finally I have added the BackgroundImage and set the FileImageSource to the ImageSource type, where as I have placed the image in the native Resource folder, as you would do with any defualt Xamarin Forms Image. 😉

Now let’s see the results… 😀

bloopscrollview-on-ios-lowq  bloopscrollview-on-android-lowq

Yaay! 😀

As we expected the Vertical and Horizontal Scrollbars are disabled and our ScrollView has full native bouncy effect accordingly.

Also you can see the Background Image nicely resized itself and fit to the background of the BloopyScrollView. 😀

Happy dance! lol

Recap Stuff…

Now there’s some stuff I wanted to recap, that is you may have noticed that when I was resizing the Image, I needed the Control’s Height and Width, and where I have acquired those properties are in two different places on each Android and iOS renderers.

To be specific I have accessed the Control’s Width and Height on Android right from the OnElementChanged method, but on iOS renderer I have accessed those values from the  OnPropertyChanged method’s Height property event. 

This is because of the differences of the Rendering cycling of Android and iOS, whereas on Android right at the firing of the Custom Renderer it assigns itself Width and Height. But on iOS we have to access them indirectly by waiting till those properties are set, by listening to the OnPropertyChanged event.

Get it on Github! 😀 XFImprovedScrollView

Cheers everyone!

Pass this on to another developer to make them smile! 😀
– Udara Alwis

Let’s resize a Bitmap and UIImage with Xamarin…

Since the beginning of computers, developers has been struggled with Images. So did I with Xamarin 😉

So here I am sharing my findings on resizing a Bitmap and UIImage respectively on Android and iOS, meanwhile preserving the aspect ratio. I’m sharing this for the ease of fellow Xamarin devs, if anyone is struggling to find a source to find solution for both Xamarin Android and iOS platforms.

Xamarin Android

Alright here goes resizing of a Bitmap on Xamarin Android, and please note that I merely convered this implementation from Java to C# when I was implementing it in my project, and here’s the reference for it : http://stackoverflow.com/a/8224161

You need to pass in the height and width you need to resize your Bitmap into. Also as you can see this resizing method scales up the Bitmap on the Y Axis, and scaling begins from the center of the Image. 🙂

private Bitmap ResizeBitmap(Bitmap originalImage, int widthToScae, int heightToScale)
{
	Bitmap resizedBitmap = Bitmap.CreateBitmap(widthToScae, heightToScale, Bitmap.Config.Argb8888);

	float originalWidth = originalImage.Width;
	float originalHeight = originalImage.Height;

	Canvas canvas = new Canvas(resizedBitmap);

	float scale = this.Width / originalWidth;

	float xTranslation = 0.0f;
	float yTranslation = (this.Height - originalHeight * scale) / 2.0f;

	Matrix transformation = new Matrix();
	transformation.PostTranslate(xTranslation, yTranslation);
	transformation.PreScale(scale, scale);

	Paint paint = new Paint();
	paint.FilterBitmap = true;

	canvas.DrawBitmap(originalImage, transformation, paint);

	return resizedBitmap;
}

 

Xamarin iOS

So below is what I used for UIImage on iOS, which I was lucky enough to find through the Xamarin Forum: https://forums.xamarin.com/discussion/comment/175585/#Comment_175585 So kudos to the original post! 🙂

public UIImage ResizeUIImage(UIImage sourceImage, float widthToScale, float heightToScale)
{
	var sourceSize = sourceImage.Size;
	var maxResizeFactor = Math.Max(widthToScale / sourceSize.Width, heightToScale / sourceSize.Height);
	if (maxResizeFactor > 1) return sourceImage;
	var width = maxResizeFactor * sourceSize.Width;
	var height = maxResizeFactor * sourceSize.Height;
	UIGraphics.BeginImageContext(new CGSize(width, height));
	sourceImage.Draw(new CGRect(0, 0, width, height));
	var resultImage = UIGraphics.GetImageFromCurrentImageContext();
	UIGraphics.EndImageContext();
	return resultImage;
}

 

Well there you have it.

Enjoy! 😀