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

不问归期 提交于 2019-12-04 10:41:53

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!