【问题标题】:How can I get a collection of all the colors in System.Drawing.Color?如何获取 System.Drawing.Color 中所有颜色的集合?
【发布时间】:2008-11-10 21:10:06
【问题描述】:

如何将 System.Drawing.Color 结构中的颜色列表提取到集合或数组中?

有没有比使用这个结构体作为基础更有效的方法来获取颜色集合?

【问题讨论】:

    标签: .net graphics


    【解决方案1】:

    所以你会这样做:

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

    ... 获取所有颜色的数组。

    或者...您可以使用反射来获取颜色。 KnownColors 包括“菜单”、系统菜单的颜色等项目。这可能不是您想要的。因此,要获取 System.Drawing.Color 中颜色的名称,您可以使用反射:

    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);
    }
    

    这会写出所有颜色,但您可以轻松定制它以将颜色名称添加到列表中。

    building a color chart 上查看此代码项目项目。

    【讨论】:

      【解决方案2】:

      试试这个:

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

      【讨论】:

        【解决方案3】:

        除了 jons911 所说的之外,如果您只想要“命名”颜色而不是像“ActiveBorder”这样的系统颜色,Color 类有一个 IsSystemColor 属性,您可以使用它来过滤掉这些颜色。

        【讨论】:

          【解决方案4】:

          这里的大多数答案都是颜色名称(字符串)的集合,而不是 System.Drawing.Color 对象。如果您需要一组实际的系统颜色,请使用:

          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】:

            Here 是一个在线页面,其中显示了每种颜色的方便样本及其名称。

            【讨论】:

              【解决方案6】:

              您必须使用反射从 System.Drawing.Color 结构中获取颜色。

              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);
              

              【讨论】:

                【解决方案7】:

                在 System.Drawing 中有一个 Enum KnownColor,它指定了已知的系统颜色。

                列表: List allColors = new List(Enum.GetNames(typeof(KnownColor)));

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

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2020-08-10
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-07-05
                  • 2011-11-19
                  • 1970-01-01
                  • 2016-01-19
                  相关资源
                  最近更新 更多