Surfing maui sources I have found worth solution.
public static async Task<Drawable> GetDrawable(this ImageSource imageSource, IElementHandler handler)
{
IImageSourceServiceProvider imageSourceServiceProvider = handler.GetRequiredService<IImageSourceServiceProvider>();
IImageSourceService service = imageSourceServiceProvider.GetImageSourceService(imageSource);
IImageSourceServiceResult<PlatformImage> result = await service.GetDrawableAsync(imageSource, handler.MauiContext.Context);
return result.Value;
}
This class is internal (as other methods I need from maui framework :) ), I just paste this to my code (maybe better to have this public?)
#if IOS || MACCATALYST
using PlatformImage = UIKit.UIImage;
using PlatformView = UIKit.UIView;
#elif ANDROID
using PlatformImage = Android.Graphics.Drawables.Drawable;
using PlatformView = Android.Views.View;
#elif WINDOWS
using PlatformImage = Microsoft.UI.Xaml.Media.ImageSource;
using PlatformView = Microsoft.UI.Xaml.FrameworkElement;
#elif TIZEN
using PlatformImage = Tizen.UIExtensions.ElmSharp.Image;
using PlatformView = ElmSharp.EvasObject;
#elif NETSTANDARD || (NET6_0 && !IOS && !ANDROID && !TIZEN)
using PlatformImage = System.Object;
using PlatformView = System.Object;
#endif
public static class ElementHandlerExtensions
{
public static IServiceProvider GetServiceProvider(this IElementHandler handler)
{
var context = handler.MauiContext ??
throw new InvalidOperationException($"Unable to find the context. The {nameof(ElementHandler.MauiContext)} property should have been set by the host.");
var services = context?.Services ??
throw new InvalidOperationException($"Unable to find the service provider. The {nameof(ElementHandler.MauiContext)} property should have been set by the host.");
return services;
}
public static T GetRequiredService<T>(this IElementHandler handler)
where T : notnull
{
var services = handler.GetServiceProvider();
var service = services.GetRequiredService<T>();
return service;
}
}
Also, this is more MAUI approach then creating handler for each type of ImageSource (Xamarin approach).