Reputation: 120
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.
Upvotes: 1
Views: 4493
Reputation: 314
This will return the English color name if it is defined:
Function GetName(color As Media.Color) As String
Dim c = System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B)
Return System.Drawing.ColorTranslator.ToHtml(c)
End Function
Upvotes: 0
Reputation: 120
My Visual Basic translation is like this:
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
I had to catch a nullreference exception, when executing this function with an unnamed color. Why, I do not know.
Upvotes: 0
Reputation:
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";
}
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"
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.
Upvotes: 9
Reputation: 15860
In the WPF, the hex code stands just as it were rgba.
#ff008000
Would be
rgba(255, 0, 80, 0); // last 2 00s are for alpha filter.
If that's the result. You should use switch statement to convert it to some String value. Also, .ToString()
method doesn't generate a Human readable String result like Green
. It just converts the result to a String while passing the value to methods and function that would require a String argument.
The following code would do the trick for you:
var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush) converter.ConvertFromString("#ff008000");
Use the brush
now.
Upvotes: 0