字符串到颜色Xamarin.Form

时间:2017-12-18 14:03:26

标签: 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
};

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

显然 Color.FromHex 会将颜色名称解析为 Color 值,例如

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

这至少适用于 Xamarin.Forms 4.2.0。我在参考文档中没有看到明确承诺的这一点,所以谁知道呢——他们将来可能会对此进行修改。看看这与 XF 5 相比如何。

答案 2 :(得分:-1)

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

try(BufferedReader br = new BufferedReader(new FileReader(pathToYourFile))) {
    String line = br.readLine();

    while (line != null) {
        // do something with your line, like printing it or appending to a StringBuilder
        System.out.println(line);
        line = br.readLine();
    }
}

更多信息here