从 System.Windows.Media.Color 中提取颜色名称 [英] Extract color name from a System.Windows.Media.Color

查看:39
本文介绍了从 System.Windows.Media.Color 中提取颜色名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 System.windows.Media.Color 对象中提取颜色名称(例如绿色")?.tostring() 方法给我十六进制格式#ff008000.

How do I extract the name of a color (e.g. "green") from a System.windows.Media.Color object? The .tostring() method gives me the hex format #ff008000.

推荐答案

您可以使用反射来获取颜色名称:

You could use reflection to get the color names:

static string GetColorName(Color col)
{
    PropertyInfo colorProperty = typeof(Colors).GetProperties()
        .FirstOrDefault(p => Color.AreClose((Color)p.GetValue(null), col));
    return colorProperty != null ? colorProperty.Name : "unnamed color";
}

以下代码展示了如何使用GetColorName():

The following code shows how to use GetColorName():

Color col = new Color { R = 255, G = 255, B = 0, A = 255 };
MessageBox.Show(GetColorName(col)); // displays "Yellow"

请注意,上面的 GetColorName() 方法不是很快,因为它使用了反射.如果您打算多次调用 GetColorName(),您可能应该将颜色表缓存在字典中.

Please note that the above GetColorName() method is not very fast, since it uses reflection. If you plan to make many calls to GetColorName(), you probably should cache the color table in a dictionary.

这篇关于从 System.Windows.Media.Color 中提取颜色名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆