Convert Xamarin.Forms.Color to platform specific color

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?

Answers


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);

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();

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);

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);

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


Need Your Help

Return results mongoose in find query to a variable

node.js mongodb mongoose mongodb-query

I need to return the results of a query with mongoose in node.js.

How do I release port 80 on a beaglebone so I can use it?

node.js port beagleboard angstrom-linux

I have a beaglebone on which I have configured lighttpd to run. Currently I have it running on port 8080 and it works fine. Except I really want to use it on port 80. Unfortunately it won't start on