将字符串转换为颜色Xamarin.Form

4
如何在Xamarin中将字符串转换为颜色?因为没有Color.fromName方法。
string colorStr = "Blue";
BoxView objBoxView = new BoxView
{
    HeightRequest = double.Parse(HeightRequest),
    HorizontalOptions = LayoutOptions.Fill,
    VerticalOptions = LayoutOptions.End,
    BackgroundColor = colorStr
};

BackgroundColor = Color.Blue 就可以了 - heinst
我知道啊,我需要将字符串转换为颜色,因为“blue”来自json文件,但是我只是简单地写了“blue”!! - manDig
1
ColorTypeConverter -> 你应该看一下这个类 - Dilmah
4个回答

8

以下是使用ColorTypeConverter与来自Xamarin.Forms github中的测试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");
}

1

很遗憾,目前没有此功能可用,但您可以尝试使用以下方法:

var strColor = "Blue";    
var color = System.Drawing.Color.FromName(strColor);
boxColor.BackgroundColor = Color.FromRgb(color.R, color.G, color.B);

0

显然, Color.FromHex 可以将颜色名称解析为一个 Color 值, 例如:

Color background = Color.FromHex("blue"); // #0000FF

至少在Xamarin.Forms 4.2.0中,这个方法是可行的。我没有在参考文档中明确看到这个承诺,所以谁知道 - 他们可能会在未来修改这个。也许可以看看这个在XF 5中的表现如何。


-1

将此转换器添加到我们的NuGet中。

using AscendantWare.Xamarin.Essentials.Tools;

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

更多信息在这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接