Code Snippet: Convert Xamarin.Forms ImageSource to Native Image


I'll share with you one code snippet that I like to use when I create some custom controls for Xamarin.Forms.

As big fan of the native experiences Im always trying to take advantage of the current types that Xamarin.Forms have allowing devs to use the extended controls and new components with the common types used on the framework, but sometimes Xamarin have some hidden implementations that are either private or internal like the way of getting a native image from an ImageSource type as you can see here(iOS):

https://github.com/xamarin/Xamarin.Forms/blob/ae5bbc51230b3a555ceed2ddce4d4fc8aaf8774d/Xamarin.Forms.Platform.iOS/Renderers/ImageElementManager.cs#L279


So for this kind of cases we can find a good solution to still use the Xamarin.Forms types and implement on your side, I'll share a piece of code that can be used on either Shared & Multi-target projects and with a single line of code you'll be able to get a native representation of an ImageSource type:


using System.Threading.Tasks;
using Xamarin.Forms;
#if __IOS__
using Xamarin.Forms.Platform.iOS;
using UIKit;
#elif __ANDROID__
using Android.Graphics;
using Xamarin.Forms.Platform.Android;
using Application = Android.App.Application;
#endif
namespace MyAwesomeExtensions
{
public static class ImageSourceExtensions
{
public static IImageSourceHandler GetDefaultHandler(this ImageSource source)
{
IImageSourceHandler handler = null;
if (source is UriImageSource)
{
handler = new ImageLoaderSourceHandler();
}
else if (source is FileImageSource)
{
handler = new FileImageSourceHandler();
}
else if (source is StreamImageSource)
{
handler = new StreamImagesourceHandler();
}
else if (source is FontImageSource)
{
handler = new FontImageSourceHandler();
}
return handler;
}
public static
#if __IOS__
Task<UIImage>
#elif __ANDROID__
Task<Bitmap>
#endif
GetNativeImageAsync(this ImageSource source)
{
if (source == null)
return null;
var nativeImageHandler = source.GetDefaultHandler();
#if __IOS__
float scale = (float)UIScreen.MainScreen.Scale;
return nativeImageHandler.LoadImageAsync(source, scale: scale);
#elif __ANDROID__
return nativeImageHandler.LoadImageAsync(source, Application.Context);
#endif
}
}
}
//for iOS UIImage and for Android Bitmap
var nativeImage = await myAwesomeImageSource.GetNativeImageAsync();
view raw Usage.cs hosted with ❤ by GitHub

As you can see is very simple to achieve it and with this you can implement good things like this one that I created as an example:


Gist:
https://gist.github.com/AlejandroRuiz/ab280fefbdf986ed8c461bd1f1d128ea

Xamarin.Forms example:
https://github.com/AlejandroRuiz/XamarinMonthCodeSnippets

Comentarios

Entradas populares