Dam*_*ien 15 .net hex colors system.drawing.color
根据问题标题,我如何获取十六进制代码并将其转换为.Net Color对象,并以其他方式执行?
我用Google搜索并继续采用不起作用的相同方式.
ColorTranslator.ToHtml(renderedChart.ForeColor)
Run Code Online (Sandbox Code Playgroud)
返回颜色的名称,如'White'而不是'#ffffff'!从另一个方面来看似乎有奇怪的结果,只在某些时候工作......
Jul*_*lia 26
就像是 :
Color color = Color.Red;
string colorString = string.Format("#{0:X2}{1:X2}{2:X2}",
color.R, color.G, color.B);
Run Code Online (Sandbox Code Playgroud)
另一方面这样做有点复杂,因为#F00是一个有效的html颜色(意思是全红色),但它仍然可以使用正则表达式,这里是一个小样本类:
using System;
using System.Diagnostics;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public static class HtmlColors
{
public static string ToHtmlHexadecimal(this Color color)
{
return string.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
}
static Regex htmlColorRegex = new Regex(
@"^#((?'R'[0-9a-f]{2})(?'G'[0-9a-f]{2})(?'B'[0-9a-f]{2}))"
+ @"|((?'R'[0-9a-f])(?'G'[0-9a-f])(?'B'[0-9a-f]))$",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
public static Color FromHtmlHexadecimal(string colorString)
{
if (colorString == null)
{
throw new ArgumentNullException("colorString");
}
var match = htmlColorRegex.Match(colorString);
if (!match.Success)
{
var msg = "The string \"{0}\" doesn't represent"
msg += "a valid HTML hexadecimal color";
msg = string.Format(msg, colorString);
throw new ArgumentException(msg,
"colorString");
}
return Color.FromArgb(
ColorComponentToValue(match.Groups["R"].Value),
ColorComponentToValue(match.Groups["G"].Value),
ColorComponentToValue(match.Groups["B"].Value));
}
static int ColorComponentToValue(string component)
{
Debug.Assert(component != null);
Debug.Assert(component.Length > 0);
Debug.Assert(component.Length <= 2);
if (component.Length == 1)
{
component += component;
}
return int.Parse(component,
System.Globalization.NumberStyles.HexNumber);
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
// Display #FF0000
Console.WriteLine(Color.Red.ToHtmlHexadecimal());
// Display #00FF00
Console.WriteLine(HtmlColors.FromHtmlHexadecimal("#0F0").ToHtmlHexadecimal());
// Display #FAF0FE
Console.WriteLine(HtmlColors.FromHtmlHexadecimal("#FAF0FE").ToHtmlHexadecimal());
Run Code Online (Sandbox Code Playgroud)
And*_*are 12
"白色" 是有效的HTML颜色.请看ColorTranslator.ToHtml:
此方法将Color结构转换为HTML颜色的字符串表示形式.这是常用的颜色名称,例如"红色","蓝色"或"绿色",而不是数字颜色值的字符串表示,例如"FF33AA".
如果您的颜色无法映射到HTML颜色字符串,则此方法将返回颜色的有效十六进制.看这个例子:
using System;
using System.Drawing;
class Program
{
static void Main()
{
Console.WriteLine(ColorTranslator.ToHtml(Color.White));
Console.WriteLine(ColorTranslator.ToHtml(Color.FromArgb(32,67,89)));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18599 次 |
| 最近记录: |