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

时间:2011-10-17 09:22:29

标签: c# winforms colors

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

我的目标是为了给定的六进制代码

获取类似“蓝色”的颜色名称

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

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

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

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

我正在使用带有c#

的winforms应用程序

9 个答案:

答案 0 :(得分:8)

我偶然发现了一个完全符合您要求的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中被删除

答案 1 :(得分:6)

使用此方法

Color myColor = ColorTranslator.FromHtml(htmlColor);

另见link

答案 2 :(得分:5)

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

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

答案 3 :(得分:1)

我想出了这个:

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

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

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

答案 6 :(得分:0)

这是一个旧帖子,但这里是一个优化的Color to 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;
    }
}

答案 7 :(得分:0)

如果您想获取颜色的名称,可以执行此操作,而无需通过以下步骤将颜色转换为十六进制:

Color c = (Color) yourColor;

yourColor.Color.Tostring;

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

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

答案 8 :(得分:0)

因为我需要一个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"/>