//
方法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);
}
// 引用命名空间 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);
}
本文转自远哥博客园博客,原文链接:http://www.cnblogs.com/taven/archive/2009/09/26/1574329.html,如需转载请自行联系原作者