如何从 System.windows.Media.Color 对象中提取颜色名称(例如“绿色”)?该.tostring()方法为我提供了十六进制格式 #ff008000。
小智 6
您可以使用反射来获取颜色名称:
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";
}
Run Code Online (Sandbox Code Playgroud)
以下代码显示了如何使用GetColorName():
Color col = new Color { R = 255, G = 255, B = 0, A = 255 };
MessageBox.Show(GetColorName(col)); // displays "Yellow"
Run Code Online (Sandbox Code Playgroud)
请注意,上述GetColorName()方法不是很快,因为它使用反射。如果您打算多次调用GetColorName(),您可能应该将颜色表缓存在字典中。
| 归档时间: |
|
| 查看次数: |
3366 次 |
| 最近记录: |