URL:http://www.cnblogs.com/taven/archive/2009/09/26/1574329.html
方法1:
引用命名空间:using System.Drawing;
16进制颜色代码转Color类型:ColorTranslator.FromHtml(color);
Color类型转16进制颜色代码:ColorTranslator.ToHtml(_color);
方法2:
/// <summary>
/// 将字符串转换为Color
/// </summary>
/// <param name="color">带#号的16进制颜色</param>
/// <returns></returns>
public Color ToColor(string color)
{
int red, green, blue = ;
char[] rgb;
color = color.TrimStart('#');
color = Regex.Replace(color.ToLower(), "[g-zG-Z]", "");
switch (color.Length)
{
case :
rgb = color.ToCharArray();
red = Convert.ToInt32(rgb[].ToString() + rgb[].ToString(), );
green = Convert.ToInt32(rgb[].ToString() + rgb[].ToString(), );
blue = Convert.ToInt32(rgb[].ToString() + rgb[].ToString(), );
return Color.FromArgb(red, green, blue);
case :
rgb = color.ToCharArray();
red = Convert.ToInt32(rgb[].ToString() + rgb[].ToString(), );
green = Convert.ToInt32(rgb[].ToString() + rgb[].ToString(), );
blue = Convert.ToInt32(rgb[].ToString() + rgb[].ToString(), );
return Color.FromArgb(red, green, blue);
default:
return Color.FromName(color);
}
}
public string ColorToHex(Color _color)
{
//return "#" + String.Format("{0:X}", Color.FromArgb(_color.R, _color.G, _color.B).ToArgb()).Substring(2);
//return Convert.ToString(Color.FromArgb(_color.R, _color.G, _color.B).ToArgb(), 16).Substring(2);
}