【问题标题】:convert hex code to color name将十六进制代码转换为颜色名称
【发布时间】:2011-12-09 03:42:09
【问题描述】:

如何将此hexa code = #2088C1 转换为颜色名称,如蓝色或红色

我的目标是我想为给定的六进制代码获得像“蓝色”这样的颜色名称

我已经尝试了下面的代码,但它没有给出任何颜色名称..

System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#2088C1");

Color col = ColorConverter.ConvertFromString("#2088C1") as Color;

但它没有给出像“aquablue”这样的颜色名称

我正在使用带有 c# 的 winforms 应用程序

【问题讨论】:

标签: c# winforms colors


【解决方案1】:

我偶然发现了一个 german site,它完全符合您的要求:

/// <summary>
/// Gets the System.Drawing.Color object from hex string.
/// </summary>
/// <param name="hexString">The hex string.</param>
/// <returns></returns>
private System.Drawing.Color GetSystemDrawingColorFromHexString(string hexString)
{
    if (!System.Text.RegularExpressions.Regex.IsMatch(hexString, @"[#]([0-9]|[a-f]|[A-F]){6}\b"))
        throw new ArgumentException();
    int red = int.Parse(hexString.Substring(1, 2), NumberStyles.HexNumber);
    int green = int.Parse(hexString.Substring(3, 2), NumberStyles.HexNumber);
    int blue = int.Parse(hexString.Substring(5, 2), NumberStyles.HexNumber);
    return Color.FromArgb(red, green, blue);
}

要获取颜色名称,您可以使用它来获取KnownColor

private KnownColor GetColor(string colorCode)
{
    Color color = GetSystemDrawingColorFromHexString(colorCode);
    return color.GetKnownColor();
}

但是,System.Color.GetKnownColor 似乎在较新版本的 .NET 中被删除了

【讨论】:

  • 谢谢,但它显示为“ff2088C1”,但我想知道该代码中的蓝色或红色等等效颜色名称
  • 我无法获得颜色。GetKnownColor();
  • KnownColor 结构代表系统颜色设置,例如 ActiveCaptionText,而不是颜色名称本身
  • 请查看我提供的链接。它显示了 KnownColor 的 MSDN 手册。还有一些系统定义的颜色被声明为 KnownColor 的值,例如珊瑚色或洋红色。
  • @MineR 请继续修复它。这似乎比投反对票更好。我已经离开 .NET 多年了,所以请原谅我对这个特定主题的无知。
【解决方案2】:

使用这个方法

Color myColor = ColorTranslator.FromHtml(htmlColor);

另见link

【讨论】:

  • 谢谢,但我想知道该代码中的蓝色或红色等等效颜色名称
【解决方案3】:

这可以通过一些反思来完成。未优化,但有效:

string GetColorName(Color color)
{
    var colorProperties = typeof(Color)
        .GetProperties(BindingFlags.Public | BindingFlags.Static)
        .Where(p => p.PropertyType == typeof(Color));
    foreach(var colorProperty in colorProperties) 
    {
        var colorPropertyValue = (Color)colorProperty.GetValue(null, null);
        if(colorPropertyValue.R == color.R 
               && colorPropertyValue.G == color.G 
               && colorPropertyValue.B == color.B) {
            return colorPropertyValue.Name;
        }
    }

    //If unknown color, fallback to the hex value
    //(or you could return null, "Unkown" or whatever you want)
    return ColorTranslator.ToHtml(color);
}

【讨论】:

  • 稍微编辑一下:colorPropertyName 不是 colorPropertyValue。感谢您的解决方案
【解决方案4】:

我刚刚想到了这个:

enum MatchType
{
  NoMatch,
  ExactMatch,
  ClosestMatch
};

static MatchType FindColour (Color colour, out string name)
{
  MatchType
    result = MatchType.NoMatch;

  int
    least_difference = 0;

  name = "";

  foreach (PropertyInfo system_colour in typeof (Color).GetProperties (BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy))
  {
    Color
      system_colour_value = (Color) system_colour.GetValue (null, null);

    if (system_colour_value == colour)
    {
      name = system_colour.Name;
      result = MatchType.ExactMatch;
      break;
    }

    int
      a = colour.A - system_colour_value.A,
      r = colour.R - system_colour_value.R,
      g = colour.G - system_colour_value.G,
      b = colour.B - system_colour_value.B,
      difference = a * a + r * r + g * g + b * b;

    if (result == MatchType.NoMatch || difference < least_difference)
    {
      result = MatchType.ClosestMatch;
      name = system_colour.Name;
      least_difference = difference;
    }
  }

  return result;
}

static void Main (string [] args)
{
  string
    colour;

  MatchType
    match_type = FindColour (Color.FromArgb (0x2088C1), out colour);

  Console.WriteLine (colour + " is the " + match_type.ToString ());

  match_type = FindColour (Color.AliceBlue, out colour);

  Console.WriteLine (colour + " is the " + match_type.ToString ());
}

【讨论】:

    【解决方案5】:

    没有现成的功能。您必须遍历已知颜色列表,并将每种已知颜色的 RGB 与未知颜色的 RGB 进行比较。

    查看此链接:http://bytes.com/topic/visual-basic-net/answers/365789-argb-color-know-color-name

    【讨论】:

      【解决方案6】:

      如果您有权访问 SharePoint 程序集,Microsoft.SharePoint 包含一个类 Microsoft.SharePoint.Utilities.ThemeColor 和一个静态方法 GetScreenNameForColor,它接受一个 System.Drawing.Color 对象并返回一个描述它的 string。大约有 20 种不同的颜色名称,它可以返回明暗变化。

      【讨论】:

        【解决方案7】:

        这是一篇旧帖子,但这里有一个优化的 Color 到 KnownColor 转换器,因为内置的 .NET ToKnownColor() 不能与 adhoc Color 结构一起正常工作。第一次调用此代码时,它会延迟加载已知的颜色值并受到轻微的性能影响。该函数的顺序调用是一个简单的字典查找和快速。

        public static class ColorExtensions
        {
            private static Lazy<Dictionary<uint, KnownColor>> knownColors = new Lazy<Dictionary<uint, KnownColor>>(() =>
            {
                Dictionary<uint, KnownColor> @out = new Dictionary<uint, KnownColor>();
                foreach (var val in Enum.GetValues(typeof(KnownColor)))
                {
                    Color col = Color.FromKnownColor((KnownColor)val);
                    @out[col.PackColor()] = (KnownColor)val;
                }
                return @out;
            });
        
            /// <summary>Packs a Color structure into a single uint (argb format).</summary>
            /// <param name="color">The color to package.</param>
            /// <returns>uint containing the packed color.</returns>
            public static uint PackColor(this Color color) => (uint)((color.A << 24) | (color.R << 16) | (color.G << 8) | (color.B << 0));
        
            /// <summary>Unpacks a uint containing a Color structure.</summary>
            /// <param name="color">The color to unpackage.</param>
            /// <returns>A new Color structure containing the color defined by color.</returns>
            public static Color UnpackColor(this uint color) => Color.FromArgb((byte)(color >> 24), (byte)(color >> 16), (byte)(color >> 8), (byte)(color >> 0));
        
            /// <summary>Gets the name of the color</summary>
            /// <param name="color">The color to get the KnownColor for.</param>
            /// <returns>A new KnownColor structure.</returns>
            public static KnownColor? GetKnownColor(this Color color)
            {
                KnownColor @out;
                if (knownColors.Value.TryGetValue(color.PackColor(), out @out))
                    return @out;
        
                return null;
            }
        }
        

        【讨论】:

          【解决方案8】:

          如果您正在寻找颜色的名称,您可以这样做,而无需通过以下方式将颜色转换为十六进制:

          Color c = (Color) yourColor;
          
          yourColor.Color.Tostring;
          

          然后删除返回的不需要的符号,大多数情况下,如果您的颜色未定义,它将返回一个 ARGB 值,在这种情况下没有内置名称,但它确实包含许多名称值。

          此外,如果您需要十六进制代码,ColorConverter 是从十六进制转换为名称的好方法。

          【讨论】:

            【解决方案9】:

            制作了一个 wpf 字符串到颜色转换器,因为我需要一个:

                 class StringColorConverter : IValueConverter
            {
                public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
                {
            
                    string colorString = value.ToString();
                    //Color colorF = (Color)ColorConverter.ConvertFromString(color); //displays r,g ,b values
                    Color colorF = ColorTranslator.FromHtml(colorString);
                    return colorF.Name;
                }
            
                public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
                {
                    throw new NotImplementedException();
                }
            }
            

            可用于

                      <TextBlock Width="40" Height="80" Background="DarkViolet" Text="{Binding Background, Converter={StaticResource StringColorConverter}, Mode=OneWay, RelativeSource={RelativeSource Self}}" Foreground="White" FontWeight="SemiBold"/>
            

            【讨论】:

              猜你喜欢
              • 2015-04-12
              • 2021-11-26
              • 2017-04-14
              • 2016-05-11
              • 1970-01-01
              • 2012-08-23
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多