//方法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 = 0;
char[] rgb;
color = color.TrimStart('#');
color = Regex.Replace(color.ToLower(), "[g-zG-Z]", "");
switch (color.Length)
{
case 3:
rgb = color.ToCharArray();
red = Convert.ToInt32(rgb[0].ToString() + rgb[0].ToString(), 16);
green = Convert.ToInt32(rgb[1].ToString() + rgb[1].ToString(), 16);
blue = Convert.ToInt32(rgb[2].ToString() + rgb[2].ToString(), 16);
return Color.FromArgb(red, green, blue);
case 6:
rgb = color.ToCharArray();
red = Convert.ToInt32(rgb[0].ToString() + rgb[1].ToString(), 16);
green = Convert.ToInt32(rgb[2].ToString() + rgb[3].ToString(), 16);
blue = Convert.ToInt32(rgb[4].ToString() + rgb[5].ToString(), 16);
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);
}
作者:Taven.李锡远
本文版权归作者所有,欢迎转载。但必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
|