Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to Color Xamarin.Form

How to convert string to color in xamarin.from , there isn't Color.fromName method ?

string colorStr = "Blue";
BoxView objBoxView = new BoxView
{
    HeightRequest = double.Parse(HeightRequest),
    HorizontalOptions = LayoutOptions.Fill,
    VerticalOptions = LayoutOptions.End,
    BackgroundColor = colorStr
};
like image 963
manDig Avatar asked Aug 31 '25 22:08

manDig


2 Answers

Some examples using ColorTypeConverter with string values from the test TestColorTypeConverter in ColorUnitTests.cs in the Xamarin.Forms github:

var input = new[]
{
    "blue", "Blue", "Color.Blue",     // by name
    "#0000ff", "#00f",                // by hex code
    "#a00f",                          // by hex code with alpha
    "rgb(0,0, 255)", "rgb(0,0, 300)", // by RGB
    "rgba(0%,0%, 100%, .8)",          // by RGB percent with alpha
    "hsl(240,100%, 50%)",             // by HSL
    "hsla(240,100%, 50%, .8)",        // by HSL with alpha
    "Accent",                         // by Accent color
    "Default", "#12345"               // not a valid color
};

ColorTypeConverter converter = new ColorTypeConverter();

foreach (var str in input)
{
    Color color = (Color)(converter.ConvertFromInvariantString(str));
    Debug.WriteLine("{0} is {1} Color", str, color.IsDefault ?  "not a" : "a");
}
like image 177
Benl Avatar answered Sep 03 '25 11:09

Benl


yeah, unfortunately there isn't, but you may use the following:

var strColor = "Blue";    
var color = System.Drawing.Color.FromName(strColor);
boxColor.BackgroundColor = Color.FromRgb(color.R, color.G, color.B);
like image 43
Gabriel G Avatar answered Sep 03 '25 12:09

Gabriel G