How can I convert a hex Color value to its human-readable string representation?

1k Views Asked by At

I want to store a color hex value (such as "#FFFF1493") as its "human-friendly" name (such as "DeepPink").

With help from SLaks and nvoigt here, I've now got this code:

if (sender is Canvas)
{
    var canvas = sender as Canvas;
    var brush = canvas.Background as SolidColorBrush;
    var color = brush.Color;
    String brushColorAsStr = color.ToString();

    IAppSettings appSettings;
    if (App.SaveSettingsLocally)
    {
        appSettings = new AppSettingLocal();
    }
    else
    {
        appSettings = new AppSettingsRemote();
    }
    appSettings.SaveSetting(VisitsConsts.APP_BAR_COLOR_SETTING, brushColorAsStr);
}

...but the value in brushColorAsStr is "#FFFF1493" (when I click the DeepPink canvas control), and that doesn't work with my code to change the app bar color based on the color selected:

String brushColor = appSettings.GetSetting(VisitsConsts.APP_BAR_COLOR_SETTING);
if (null == brushColor) return;

if (brushColor.Equals("Blue"))
{
    CmdBar.Background = new SolidColorBrush(Colors.Blue);
}
else if (brushColor.Equals("Aqua"))
. . .

From here I got these suggestions:

Color colour = (Color)ColorConverter.ConvertFromString(brushColorAsStr);
System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml(brushColorAsStr);

...but "ColorConverter" and "Drawing" are unresolvable in my app. How can I get a human-readable name from a hex color val?

2

There are 2 best solutions below

0
On BEST ANSWER

There isn't a mapping from numbers to names, but the Colors class maps from names to numbers. You can use reflection to build the reverse mapping.

See this previous answer for sample code: How to convert a Windows.UI.Color into a string color name in a Windows Universal app

1
On