Reputation: 1268
I'm looking for a way to convert a Xamarin.Forms.Color to a platform specific color. For example the Android.Graphics.Color for Android.
I took a look at the properties of the Xamarin.Forms.Color like R, G & B. The values only contain a 0 or 1 so that seems to be pretty worthless. Has someone experienced and solved this issue before?
Upvotes: 24
Views: 18370
Reputation: 2348
Solution using Xamarin.Essentials
:
var xfColor = Xamarin.Forms.Color.FromRgba(219, 52, 152, 255);
// Extension to convert
// using Xamarin.Essentials;
var platformColor = xfColor.ToPlatformColor();
Link: https://learn.microsoft.com/en-us/xamarin/essentials/color-converters
Upvotes: 0
Reputation: 1668
Xamarin have added ToWindowsColor()
(I think at 3.6 release). ->
Then it's just needed to do.. YourColorObject.ToWindowsColor()
and then you've a Windows.UI.Color
Upvotes: 0
Reputation: 20279
Here are some approaches for Windows:
Take e.g. this extension:
using System;
namespace Xamarin.Forms.Platform.WinRT
{
public static class ColorExtensions
{
public static Windows.UI.Color ToWindows(this Xamarin.Forms.Color color)
{
return Windows.UI.Color.FromArgb(Convert.ToByte(color.A * 255), Convert.ToByte(color.R * 255), Convert.ToByte(color.G * 255), Convert.ToByte(color.B * 255));
}
}
}
Or use a Brush
directly like here:
var converter = new ColorConverter();
Control.CurrentBrush =
(SolidColorBrush)
converter.Convert(Element.CurrentLineColor, null, null, null);
Upvotes: 3
Reputation: 2373
Going off of the previous answers here, but Xamarin has now placed the ToAndroid() method in a ColorExtensions helper class.
using Xamarin.Forms.Platform.Android
....
Android.Graphics.Color color = ColorExtensions.ToAndroid(formsColor);
Upvotes: 3
Reputation: 171
Currently you can do this with the "ToAndroid()" extension method in Xamarin.Forms.Platform.Android.
using Xamarin.Forms.Platform.Android;
Android.Graphics.Color droidColor = formsColor.ToAndroid();
Upvotes: 16
Reputation: 16222
I guess you try to do this in a custom renderer.
In iOS, you'd do:
UIColor uicolor = yourXFColor.ToUIColor ();
In Android:
Android.Graphics.Color adColor = yourXFColor.ToAndroidColor ();
Unfortunately, the equivalent extension methods are not public for WP, but you can do this:
System.Windows.Media.Color wpColor = System.Windows.Media.Color.FromArgb (
(byte)(yourXFColor.A * 255),
(byte)(yourXFColor.R * 255),
(byte)(yourXFColor.G * 255),
(byte)(yourXFColor.B * 255));
then eventually:
Brush brush = new SolidColorBrush (wpColor);
Upvotes: 65