【问题标题】:How can i get a list of the extended html colors in .NET?如何在 .NET 中获取扩展的 html 颜色列表?
【发布时间】:2015-12-24 23:49:12
【问题描述】:

我很想得到一个扩展的 html 颜色列表,就像显示的那些 here

我需要颜色名称和 Html 值。 .net 中有什么可用的功能吗?

【问题讨论】:

    标签: .net


    【解决方案1】:

    应该这样做:

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

    【讨论】:

      【解决方案2】:

      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 颜色。

      【讨论】:

      • 您好,我怎样才能将其转换为 Hex 值而不是 RGB?
      • @OrElse 不知道不是“#rrggbb”的“十六进制”值是什么。对于后者,Magnus 已经给出了代码。
      【解决方案3】:

      这是另一种方法,我发现的最短和最简单的方法:

      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/2321042https://stackoverflow.com/a/28777828/2321042

      【讨论】:

        猜你喜欢
        • 2013-09-07
        • 2018-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-12
        • 1970-01-01
        • 2016-08-10
        相关资源
        最近更新 更多