【发布时间】:2015-12-24 23:49:12
【问题描述】:
我很想得到一个扩展的 html 颜色列表,就像显示的那些 here
我需要颜色名称和 Html 值。 .net 中有什么可用的功能吗?
【问题讨论】:
标签: .net
我很想得到一个扩展的 html 颜色列表,就像显示的那些 here
我需要颜色名称和 Html 值。 .net 中有什么可用的功能吗?
【问题讨论】:
标签: .net
应该这样做:
var colors =
Enum.GetValues(typeof(KnownColor)).Cast<KnownColor>()
.Select(k => Color.FromKnownColor(k))
.Where(k => !k.IsSystemColor)
如果您需要十六进制和名称,只需附加:
.Select (k => new
{
Name = k.Name,
Hex = "#" + k.R.ToString("X2") +
k.G.ToString("X2") +
k.B.ToString("X2")
});
【讨论】:
System.Drawing.Color 用于 .NET 中的颜色(包括 HTML 颜色)。该类型具有所有 CSS3 colors 作为其静态属性,因此可以通过反射检索它们。 KnownColors 也包含列表,但它也有不相关的颜色。
typeof(Color).GetProperties(BindingFlags.Static|BindingFlags.Public)
/*.Where(p=>p.PropertyType == typeof(Color)) */ /* a possible extra precaution:
* currently, they are all Color.
* My way is to let the code break on casting instead if anything changes
* to draw attention to the change.
* You may also validate the total number against the spec (141)
* (the table in the spec actually has 148 entries 'cuz it has both
* "gray" and "grey" spellings). */
.Select(p=>(Color)(p.GetValue(null,null)))
请注意,该列表包含您可能想要也可能不想要的 Color.Transparent,因为它也是一种有效的 CSS 颜色。
【讨论】:
这是另一种方法,我发现的最短和最简单的方法:
foreach (Color col in new ColorConverter().GetStandardValues())
{
if (!col.IsSystemColor)
Console.WriteLine("{0} {1}", col.Name, ColorTranslator.ToHtml(Color.FromArgb(col.ToArgb())));
}
另一种获取html代码的方法:
Console.WriteLine("{0} #{1}", col.Name, Color.FromArgb(col.ToArgb()).Name.Substring(2).ToUpper());
这些答案的功劳: https://stackoverflow.com/a/3821216/2321042 和 https://stackoverflow.com/a/28777828/2321042
【讨论】: