Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Windows.UI.Color into a string color name in a Windows Universal app

I'm trying to convert a Windows.UI.Color into a simple string color name in my Windows 8.1 Universal app.

I already have the ARGB values from the Color (even the hex code), and I just want its associated known name (for example, from #7AFF7A7A to "salmon"). Since System.Drawing is not available in WinRT, I cannot use ColorConverter or ColorTranslator.

I've tried converting the Windows.UI.Color object into a SolidColorBrush or even a Brush, but none of them provide the name conversion capability.

What's the best way of doing this?

like image 688
irodrisa Avatar asked Mar 18 '23 07:03

irodrisa


2 Answers

The Colors class contains named properties for many colors. There isn't a canned reverse lookup, but you can use reflection to build your own mapping from color to color name.

Dictionary<Color, string> ColorNames = new Dictionary<Color, string>();
foreach (var color in typeof(Colors).GetRuntimeProperties())
{
    ColorNames[(Color)color.GetValue(null)] = color.Name;
}

Test:

Color c = Colors.AliceBlue;
Debug.WriteLine("{0} is {1}", c, ColorNames[c]);

Result:

#FFF0F8FF is AliceBlue

Watch out for duplicates (e.g. Colors.Aqua and Colors.Cyan both map to #FF00FFFF). My loop will prefer the second.

Depending on where your Color objects from you may want to key off of the string hex value rather than the Color object itself, and if you get really clever you could do a nearest match rather than exact only (implementation left as an exercise for the reader :) )

--Rob

like image 63
Rob Caplan - MSFT Avatar answered Apr 09 '23 00:04

Rob Caplan - MSFT


You can just use the ColorHelper.ToDisplayName:

var c = Color.FromArgb(255, 255, 0, 0);
Debug.WriteLine("{0} is {1}", c, ColorHelper.ToDisplayName(c));

Result:

#FFFF0000 is Red
like image 23
Michael Hawker - MSFT Avatar answered Apr 08 '23 23:04

Michael Hawker - MSFT