为 Xamarin.Form 着色的字符串

man*_*Dig 1 c# colors xamarin.forms

如何在 xamarin.from 中将字符串转换为颜色,没有 Color.fromName 方法?

string colorStr = "Blue";
BoxView objBoxView = new BoxView
{
    HeightRequest = double.Parse(HeightRequest),
    HorizontalOptions = LayoutOptions.Fill,
    VerticalOptions = LayoutOptions.End,
    BackgroundColor = colorStr
};
Run Code Online (Sandbox Code Playgroud)

Ben*_*enl 5

使用 ColorTypeConverter 和Xamarin.Forms github中 ColorUnitTests.cs 中测试 TestColorTypeConverter 的字符串值的一些示例:

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");
}
Run Code Online (Sandbox Code Playgroud)