String to Color Xamarin.Form

烂漫一生 提交于 2020-11-29 18:57:58

问题


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

回答1:


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



回答2:


Added this converter into our NuGet.

using AscendantWare.Xamarin.Essentials.Tools;

String MyColor = "Red";
Color cRed = MyColor.ToColor();

More Informations here.



来源:https://stackoverflow.com/questions/47870119/string-to-color-xamarin-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!