将十六进制代码转换为颜色名称

本文关键字:颜色 转换 十六进制 代码 | 更新日期: 2023-09-27 18:11:21

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

我的目标是我想得到的颜色名称,如"蓝色"为给定的十六进制代码

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

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

但是它没有给出像"aquablue"这样的颜色名称

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

将十六进制代码转换为颜色名称

我偶然发现了一个德国网站,它可以完全满足你的需求:

/// <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版本中被删除了

使用此方法

Color myColor = ColorTranslator.FromHtml(htmlColor);

另见链接

这可以通过一些反射来完成。没有优化,但它工作:

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

我刚想到这个:

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

没有现成的函数。你必须浏览已知颜色列表,并将每种已知颜色的RGB与未知颜色的RGB进行比较。

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

这是一个旧的帖子,但这里是一个优化的颜色到KnownColor转换器,因为在。net中内置的ToKnownColor()不能正确地工作与特殊的颜色结构。第一次调用这段代码时,它将惰性加载已知的颜色值并进行轻微的优化。顺序调用该函数是一个简单的字典查找和快速。

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

如果您希望获得颜色的名称,您可以这样做,而无需通过以下步骤将颜色转换为十六进制:

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

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

此外,ColorConverter是一个很好的方式,从十六进制转换到名称,如果你需要有十六进制代码。

为颜色转换器制作了一个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"/>

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