我需要将一些颜色(十六进制)转换为Brush。 我需要在代码中执行此操作。
我该怎么办?
答案 0 :(得分:12)
//this would be initialized somewhere else, I assume
string hex = "#00E4FF";
//strip out any # if they exist
hex = hex.Replace("#", string.Empty);
byte r = (byte)(Convert.ToUInt32(hex.Substring(0, 2), 16));
byte g = (byte)(Convert.ToUInt32(hex.Substring(2, 2), 16));
byte b = (byte)(Convert.ToUInt32(hex.Substring(4, 2), 16));
SolidColorBrush myBrush = new SolidColorBrush(Color.FromArgb(255, r, g, b));
答案 1 :(得分:11)
我需要其中一个也适用于3位“速记十六进制形式”和MS alpha通道版本(适用于 Silverlight / WPF ),所以想出这个版本来涵盖所有< em> numeric 颜色格式:
/// <summary>
/// Convert a Hex color string to a Color object
/// </summary>
/// <param name="htmlColor">Color string in #rgb, #argb, #rrggbb or #aarrggbb format</param>
/// <returns>A color object</returns>
public static Color ColorFromString(string htmlColor)
{
htmlColor = htmlColor.Replace("#", "");
byte a = 0xff, r = 0, g = 0, b = 0;
switch (htmlColor.Length)
{
case 3:
r = byte.Parse(htmlColor.Substring(0, 1), System.Globalization.NumberStyles.HexNumber);
g = byte.Parse(htmlColor.Substring(1, 1), System.Globalization.NumberStyles.HexNumber);
b = byte.Parse(htmlColor.Substring(2, 1), System.Globalization.NumberStyles.HexNumber);
break;
case 4:
a = byte.Parse(htmlColor.Substring(0, 1), System.Globalization.NumberStyles.HexNumber);
r = byte.Parse(htmlColor.Substring(1, 1), System.Globalization.NumberStyles.HexNumber);
g = byte.Parse(htmlColor.Substring(2, 1), System.Globalization.NumberStyles.HexNumber);
b = byte.Parse(htmlColor.Substring(3, 1), System.Globalization.NumberStyles.HexNumber);
break;
case 6:
r = byte.Parse(htmlColor.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
g = byte.Parse(htmlColor.Substring(2, 2), System.Globalization.NumberStyles.HexNumber);
b = byte.Parse(htmlColor.Substring(4, 2), System.Globalization.NumberStyles.HexNumber);
break;
case 8:
a = byte.Parse(htmlColor.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
r = byte.Parse(htmlColor.Substring(2, 2), System.Globalization.NumberStyles.HexNumber);
g = byte.Parse(htmlColor.Substring(4, 2), System.Globalization.NumberStyles.HexNumber);
b = byte.Parse(htmlColor.Substring(6, 2), System.Globalization.NumberStyles.HexNumber);
break;
}
return Color.FromArgb(a, r, g, b);
}
对于画笔,你可以这样使用它:
return new SolidColorBrush(ColorFromString(colorString));
使用byte.Parse比转换更有效,不需要转换。
更新: 修复了案例8的子字符串偏移。
答案 2 :(得分:0)
public static SolidColorBrush GetColorFromHexa(string hexaColor)
{
return new SolidColorBrush(Color.FromArgb(
Convert.ToByte(hexaColor.Substring(1, 2), 16),
Convert.ToByte(hexaColor.Substring(3, 2), 16),
Convert.ToByte(hexaColor.Substring(5, 2), 16),
Convert.ToByte(hexaColor.Substring(7, 2), 16)
)
);
}
希望这有帮助