How can I get a collection of all the colors in System.Drawing.Color?

人盡茶涼 提交于 2020-01-01 09:08:23

问题


How can I extract the list of colors in the System.Drawing.Color struct into a collection or array?

Is there a more efficient way of getting a collection of colors than using this struct as a base?


回答1:


So you'd do:

string[] colors = Enum.GetNames(typeof(System.Drawing.KnownColor));

... to get an array of all the collors.

Or... You could use reflection to just get the colors. KnownColors includes items like "Menu", the color of the system menus, etc. this might not be what you desired. So, to get just the names of the colors in System.Drawing.Color, you could use reflection:

Type colorType = typeof(System.Drawing.Color);

PropertyInfo[] propInfoList = colorType.GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);

foreach (System.Reflection.PropertyInfo c in propInfoList) {
  Console.WriteLine(c.Name);
}

This writes out all the colors, but you could easily tailor it to add the color names to a list.

Check out this Code Project project on building a color chart.




回答2:


Try this:

foreach (KnownColor knownColor in Enum.GetValues(typeof(KnownColor)))
{
   Trace.WriteLine(string.Format("{0}", knownColor));
}



回答3:


In addition to what jons911 said, if you only want the "named" colors and not the system colors like "ActiveBorder", the Color class has an IsSystemColor property that you can use to filter those out.




回答4:


Most of the answers here result in a collection of color names (strings) instead of System.Drawing.Color objects. If you need a collection of actual system colors, use this:

using System.Collections.Generic;
using System.Drawing;
using System.Linq;
...
static IEnumerable<Color> GetSystemColors() {
    Type type = typeof(Color);
    return type.GetProperties().Where(info => info.PropertyType == type).Select(info => (Color)info.GetValue(null, null));
}



回答5:


In System.Drawing there is an Enum KnownColor, it specifies the known system colors.

List<>: List allColors = new List(Enum.GetNames(typeof(KnownColor)));

Array[] string[] allColors = Enum.GetNames(typeof(KnownColor));




回答6:


Here is an online page that shows a handy swatch of each color along with its name.




回答7:


You'll have to use reflection to get the colors from the System.Drawing.Color struct.

System.Collections.Generic.List<string> colors = 
        new System.Collections.Generic.List<string>();
Type t = typeof(System.Drawing.Color);
System.Reflection.PropertyInfo[] infos = t.GetProperties();
foreach (System.Reflection.PropertyInfo info in infos)
    if (info.PropertyType == typeof(System.Drawing.Color))
        colors.Add(info.Name);


来源:https://stackoverflow.com/questions/279190/how-can-i-get-a-collection-of-all-the-colors-in-system-drawing-color

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!