2017-12-18 200 views
-2

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

string colorStr = "Blue"; 
BoxView objBoxView = new BoxView 
{ 
    HeightRequest = double.Parse(HeightRequest), 
    HorizontalOptions = LayoutOptions.Fill, 
    VerticalOptions = LayoutOptions.End, 
    BackgroundColor = colorStr 
}; 
+0

'BACKGROUNDCOLOR = Color.Blue'会做 – heinst

+0

Maaan我知道,我需要字符串转换颜色,因为“蓝色”来自JSON文件,但我简单地写了“蓝色”! – manDig

+1

ColorTypeConverter - >你应该看看这个类 – Dilmah

回答

0

Xamarin.Forms github在ColorUnitTests.cs使用ColorTypeConverter从测试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"); 
}