开发者

System.Windows.Media.Color to color name

开发者 https://www.devze.com 2023-01-19 20:26 出处:网络
I have the following: Color color = Colors.Red; color.ToString(); 开发者_运维技巧 which outputs as the hexadecimal representation. Is there any way to output \"Red\"?

I have the following:

Color color = Colors.Red;
color.ToString();
开发者_运维技巧

which outputs as the hexadecimal representation. Is there any way to output "Red"?

Bonus points to whoever gives a solutions that works with different cultures (i.e. output "Rojo" for spanish).


It looks like you might have to hand-roll your own solution using Reflection. Here's my first shot:

public static string GetColorName(this System.Windows.Media.Color color)
{
    Type colors = typeof(System.Windows.Media.Colors);
    foreach(var prop in colors.GetProperties())
    {
        if(((System.Windows.Media.Color)prop.GetValue(null, null)) == color)
            return prop.Name;
    }

    throw new Exception("The provided Color is not named.");
}

Keep in mind that this is by no means efficient, but from what I can see in the documentation it would be the only way.


One option might be to convert the Media.Color to a Drawing.Color

private System.Drawing.Color ColorFromMediaColor(System.Windows.Media.Color clr)
{
  return System.Drawing.Color.FromArgb(clr.A, clr.R, clr.G, clr.B);
}

Then use the Name property from the Drawing.Color object to get the color name.

As for localizing, you could look up the color name in a translation dictionary built from resource files you provide.

0

精彩评论

暂无评论...
验证码 换一张
取 消