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

C# 将十六进制代码转换为颜色名称,c#,winforms,colors,C#,Winforms,Colors,如何将此hexa code=2088C1转换为蓝色或红色等颜色名称 我的目标是为给定的hexa代码获得类似“蓝色”的颜色名称 我试过下面的代码,但没有给出任何颜色名称 System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#2088C1"); Color col = ColorConverter.ConvertFromString("#2088C1") as Color; 但它并没有给颜色起这样的名字“水蓝色”

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

我的目标是为给定的hexa代码获得类似“蓝色”的颜色名称

我试过下面的代码,但没有给出任何颜色名称

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

Color col = ColorConverter.ConvertFromString("#2088C1") as Color;
但它并没有给颜色起这样的名字“水蓝色”

我正在将winforms应用程序与c#

一起使用,我偶然发现了一个完全符合您要求的:

/// <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);
}
但是,
System.Color.GetKnownColor
似乎在较新版本的.NET中被删除

请使用此方法

Color myColor = ColorTranslator.FromHtml(htmlColor);

另请参见

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


查看此链接:

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

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

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 ());
}
枚举匹配类型
{
流浪者,
精确匹配,
密切配合
};
静态匹配类型FindColor(颜色、输出字符串名称)
{
火柴类型
结果=MatchType.NoMatch;
int
最小_差=0;
name=“”;
foreach(PropertyInfo system_Color in typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.flattHierarchy))
{
颜色
system_Color_value=(Color)system_Color.GetValue(null,null);
if(系统颜色值==颜色)
{
名称=系统颜色名称;
结果=MatchType.ExactMatch;
打破
}
int
a=颜色.a-系统颜色值.a,
r=颜色.r-系统颜色值.r,
g=颜色.g-系统颜色.g,
b=颜色.b-系统颜色值.b,
差=a*a+r*r+g*g+b*b;
if(结果==MatchType.NoMatch | |差<最小_差)
{
结果=MatchType.ClosesMatch;
名称=系统颜色名称;
最小差异=差异;
}
}
返回结果;
}
静态void Main(字符串[]参数)
{
一串
颜色;
火柴类型
match_type=findColor(Color.FromArgb(0x2088C1),输出颜色);
Console.WriteLine(color+”是“+match_type.ToString());
match_type=findColor(Color.AliceBlue,out Color);
Console.WriteLine(color+”是“+match_type.ToString());
}

这是一篇老文章,但这里有一个经过优化的颜色到颜色转换器,因为内置的.NET ToKnownColor()无法正确使用adhoc颜色结构。第一次调用此代码时,它将延迟加载已知的颜色值,并受到较小的性能影响。对函数的顺序调用是一个简单的字典查找和快速调用

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;
    }
}
公共静态类扩展
{
私有静态惰性知识颜色=新惰性(()=>
{
Dictionary@out=newdictionary();
foreach(Enum.GetValues中的var val(typeof(KnownColor)))
{
Color col=Color.FROMKNOWNCLOR((KNOWNCLOR)val);
@out[col.PackColor()]=(KnownColor)val;
}
返回@out;
});
///将颜色结构打包为单个uint(argb格式)。
///包装的颜色。
///包含包装颜色的单元。
公共静态uint PackColor(该颜色)=>(uint)((Color.A>16),(字节)(Color>>8),(字节)(Color>>0));
///获取颜色的名称
///要获取已知颜色的颜色。
///一种新的已知颜色结构。
公共静态KnownColor?GetKnownColor(此颜色)
{
KnownColor@out;
if(knownColors.Value.TryGetValue(color.PackColor(),out@out))
返回@out;
返回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"/>


您需要它做什么?看到更大的图片可能会帮助我们更好地帮助您。谁说
2088C1
是水蓝色的?可能是重复的谢谢,但它显示的是这样的“ff2088C1”,但我想知道类似于蓝色或红色的颜色名称我无法从代码中获得颜色。GetKnownColor();KnownColor结构表示系统颜色设置,如ActiveCaptionText,而不是颜色名称本身。请查看我提供的链接。它显示了KnownColor的MSDN手册。还有一些系统定义的颜色表示为KnownColor的值,例如珊瑚色或洋红。@MineR请继续并修复它。这似乎比向下投票更好。我已经离开.NET很多年了,所以请原谅我对这一特定主题的无知。谢谢,但我想知道代码中类似蓝色或红色的颜色名称只要稍微编辑一下:只有
colorProperty
具有
名称
而不是
colorPropertyValue
。谢谢你的解决方案
          <TextBlock Width="40" Height="80" Background="DarkViolet" Text="{Binding Background, Converter={StaticResource StringColorConverter}, Mode=OneWay, RelativeSource={RelativeSource Self}}" Foreground="White" FontWeight="SemiBold"/>