UPDATE:
You can now find an extension method to do this in the following namespace.
using Microsoft.Maui.Platform;
And then you can use it like so:
color.ToPlatform(); // here color is a Maui.Graphics.Color
OG answer:
Well, I could not find a direct helper method/class to do this so I just created some extension methods to do this:
#if ANDROID
using NativeColor = Android.Graphics.Color;
#endif
#if IOS
using NativeColor = UIKit.UIColor;
#endif
public static class Extensions
{
/// <summary>
/// Get native color from maui color
/// </summary>
/// <param name="color"></param>
/// <returns>native Color</returns>
public static NativeColor ToNativeColor(this Color color)
{
var hexCode = color.ToHex();
NativeColor nativeColor;
#if ANDROID
nativeColor= Android.Graphics.Color.ParseColor(hexCode);
#endif
#if IOS
nativeColor = UIKit.UIColor.Clear.FromHex(hexCode);
#endif
return nativeColor;
}
#if IOS
public static UIColor FromHex(this UIColor color, string hex)
{
int r = 0, g = 0, b = 0, a = 0;
if (hex.Contains("#"))
hex = hex.Replace("#", "");
switch (hex.Length)
{
case 2:
r = int.Parse(hex, System.Globalization.NumberStyles.AllowHexSpecifier);
g = int.Parse(hex, System.Globalization.NumberStyles.AllowHexSpecifier);
b = int.Parse(hex, System.Globalization.NumberStyles.AllowHexSpecifier);
a = 255;
break;
case 3:
r = int.Parse(hex.Substring(0, 1), System.Globalization.NumberStyles.AllowHexSpecifier);
g = int.Parse(hex.Substring(1, 1), System.Globalization.NumberStyles.AllowHexSpecifier);
b = int.Parse(hex.Substring(2, 1), System.Globalization.NumberStyles.AllowHexSpecifier);
a = 255;
break;
case 4:
r = int.Parse(hex.Substring(0, 1), System.Globalization.NumberStyles.AllowHexSpecifier);
g = int.Parse(hex.Substring(1, 1), System.Globalization.NumberStyles.AllowHexSpecifier);
b = int.Parse(hex.Substring(2, 1), System.Globalization.NumberStyles.AllowHexSpecifier);
a = int.Parse(hex.Substring(3, 1), System.Globalization.NumberStyles.AllowHexSpecifier);
break;
case 6:
r = int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
g = int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
b = int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
a = 255;
break;
case 8:
r = int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
g = int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
b = int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
a = int.Parse(hex.Substring(6, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
break;
}
return UIColor.FromRGBA(r, g, b, a);
}
#endif
}
I hope this helps someone, Not sure if this is the best solution so if you have something better please let me know so I can update this :)