WinRT/Metro: 解析颜色字符串
字符串转换成颜色,这个在WPF中可以一句话搞定的事情:
var color = (Color)ColorConverter.ConvertFromString("#FF293C69");
但是在WinRT中没有响应的方法支持,唯一一个初始化Color的方法就是Windows.UI.ColorHelper类型的FromArgs方法,参数是4个byte。
因此写了个方法,把颜色字符串直接转换成SolidColorBrush。该方法可以解析的字符串对#和Alpha值得存在没有要求。也就是说以下值都可以被正确解析(没带Alpha当然默认Alpha为FF):
#FF293C69 #293C69 FF293C69 293C69
代码:
//+ using System.Globalization;
//+ using Windows.UI;
SolidColorBrush GetSolidColorBrush(string color)
{
if (color == null)
throw new ArgumentNullException("color");
try
{
//去掉#
if (color.StartsWith("#"))
color = color.Substring(1);
//将字符串解析成完整的int
byte a, r, g, b;
int integer = Int32.Parse(color, NumberStyles.HexNumber);
//判断或解析Alpha
if (color.Length == 6)
a = 255;
else
a = (byte)((integer >> 24) & 255);
//解析RGB
r = (byte)((integer >> 16) & 255);
g = (byte)((integer >> 8) & 255);
b = (byte)(integer & 255);
return new SolidColorBrush(ColorHelper.FromArgb(a, r, g, b));
}
catch (Exception ex)
{
throw new FormatException("无法解析的颜色", ex);
}
}
TAG: