Jor*_*dan 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));
Run Code Online (Sandbox Code Playgroud)
Gon*_*ing 11
我需要其中一个也适用于3位"速记十六进制形式"和MS alpha通道版本(用于Silverlight/WPF),因此想出这个版本来涵盖所有数字颜色格式:
/// <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);
}
Run Code Online (Sandbox Code Playgroud)
对于画笔,你可以像这样使用它:
return new SolidColorBrush(ColorFromString(colorString));
Run Code Online (Sandbox Code Playgroud)
使用byte.Parse比Convert更有效,不需要强制转换.
更新:修复了案例8的子字符串偏移.
归档时间: |
|
查看次数: |
10410 次 |
最近记录: |