The default Xamarin Forms ImageSource is good, but it doesn’t provide all the properties of an Image, not as much as native Image types of Android or iOS. This is why sometimes we need to drill down to the native level of Image handling sometimes, specially when you’re dealing with Custom Renderers, or complex Image manipulation stuff in Xamarin.
So yeah it’s no surprise you will run into the need of converting the default Xamarin Forms ImageSource to native Image type in iOS and Android, respectively UIImage or Bitmap types.
Well I know I did. lol 😛
How ? 😮
So how could you do this ? Well, something intermediate for both Xamarin Forms ImageSource and the native Image types is the byte array. 🙂 But I’m gonna take a pass on it, since it’s too much of trouble and process, which could lead to bad memory consumption. 😦 Instead, why don’t we deal with this straight away. 😀
This is how I did it.. 😉
Now when it comes to Xamarin Forms almost everything is handled by drilling down to the native levels of the platform. Likewise ImageSource during the runtime is handled through three types of Native Handlers that are as follows,
Now for each Native environment, these handlers implements a LoadImageAsync() method, which loads the type of Native Type image for a given ImageSource.
This is usually done under the hood, but we need to access this same functionality on the go for our own requirements, so let’s do it by our own implementation.
Let’s create our Android Image Helper…
So we are going to create a Public class with static methods that could be used as extension methods in our Native Project levels. So go ahead and create the AndroidImageHelper class in your Xamarin.Android project level.
Alright there we go, as you would have expected we are using the native level Handlers of the ImageSource and retrieving the native image type as I explained earlier through the LoadImageAsync() method. Of course you need to pass a reference of your current Context since Android requires the context reference to almost every execution related to the UI stuff.
First we are getting the GetHandler type by the ImageSource, then we are calling the method above to retrieve the Bitmap image and returns back to the caller.
Let’s create our iOS Image Helper…
So just like on Android let’s do the same on iOS and create the public class IosImageHelper in your Xamarin Forms iOS project level.
So here also we are using the same implementation as we used on Android, instead the LoadImageAsync() returns an UIImage.
Now let’s use it… 😉
Alright let’s see how to use these extensions in our code. 🙂
There you have it, now you have your Xamarin Forms ImageSource converted to the given Native Image type, either iOS UIImage or Android Bitmap Image type. 😀