As noted in comments, the KnownColor
enumeration can be used to make this simpler:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
class Test
{
static void Main()
{
Color color = Color.FromArgb(255, 0, 0);
Console.WriteLine(color.Name); // ffff0000
var colorLookup = Enum.GetValues(typeof(KnownColor))
.Cast<KnownColor>()
.Select(Color.FromKnownColor)
.ToLookup(c => c.ToArgb());
// There are some colours with multiple entries...
foreach (var namedColor in colorLookup[color.ToArgb()])
{
Console.WriteLine(namedColor.Name);
}
}
}
Original answer
Color.FromArgb
will give you a Color
, but it will never have a name. You need to use reflection to get the named colours, as far as I'm aware.
Here's another version of Cole Campbell's solution which I was working up at the same time...
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
class Test
{
static void Main()
{
Color color = Color.FromArgb(255, 0, 0);
Console.WriteLine(color.Name); // ffff0000
var colorLookup = typeof(Color)
.GetProperties(BindingFlags.Public | BindingFlags.Static)
.Select(f => (Color) f.GetValue(null, null))
.Where(c => c.IsNamedColor)
.ToLookup(c => c.ToArgb());
// There are some colours with multiple entries...
foreach (var namedColor in colorLookup[color.ToArgb()])
{
Console.WriteLine(namedColor.Name);
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…