2014-06-28 70 views

回答

2

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

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

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

请注意,上述GetColorName()方法不是非常快,因为它使用反射。如果您打算拨打GetColorName(),您可能应该在字典中缓存颜色表。

+0

谢谢!它解决了!我会在明天发布你的答案翻译成VB! –

0

在WPF中,十六进制代码就像它是rgba一样。

#ff008000 

rgba(255, 0, 80, 0); // last 2 00s are for alpha filter. 

如果是这样的结果。您应该使用switch语句将其转换为某个String值。此外,.ToString()方法不会生成像Green这样的人类可读字符串结果。它只是将结果转换为字符串,而将值传递给需要String参数的方法和函数。

下面的代码会做的伎俩为您提供:

var converter = new System.Windows.Media.BrushConverter(); 
var brush = (Brush) converter.ConvertFromString("#ff008000"); 

现在使用brush

+0

谢谢!因为我“说”VB我不得不将C#翻译成VB,而且它运行良好: –

+0

呵呵,呵呵我从来不知道你在用VB。抱歉! –

0

我的Visual Basic的翻译是这样的:

Function GetColorName(ByVal col As System.Windows.Media.Color) As String 

    Dim coltype As System.Type = GetType(System.Windows.Media.Colors) 
    Dim colproplist() As PropertyInfo = coltype.GetProperties 

    Try 

     Dim colorproperty As PropertyInfo = colproplist.FirstOrDefault(Function(p As PropertyInfo) Color.AreClose(p.GetValue(col, Nothing), col)) 

     Return colorproperty.Name 

    Catch ex As Exception 

     Return ("unnamed color") 

    End Try 

End Function 

我不得不搭上nullreference例外,一位不愿透露姓名的颜色在执行此功能时。为什么,我不知道。