Home > Posts > HowTo: List all known color names and find name of given color at WPF

HowTo: List all known color names and find name of given color at WPF

This is my answer at
http://stackoverflow.com/questions/4475391/wpf-silverlight-find-the-name-of-a-color

Modified answer from Thomas Levesque to populate the Dictionary only when 1st needed, instead of taking the cost at startup (going to use at speech recognition-driven turtle graphics, so that user can pronounce known color names to change the turtle’s pen color)

  1. //Project: SpeechTurtle (http://SpeechTurtle.codeplex.com)
  2. //Filename: ColorUtils.cs
  3. //Version: 20150901
  4.  
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Windows.Media;
  9.  
  10. namespace SpeechTurtle.Utils
  11. {
  12.   /// <summary>
  13.   /// Color-related utility methods
  14.   /// </summary>
  15.   public static class ColorUtils //based on http://stackoverflow.com/questions/4475391/wpf-silverlight-find-the-name-of-a-color
  16.   {
  17.     #region — Fields —
  18.  
  19.     private static Dictionary<string, Color> knownColors; //=null
  20.  
  21.     #endregion
  22.  
  23.     #region — Methods —
  24.  
  25.     #region Extension methods
  26.  
  27.     public static string GetKnownColorName(this Color color)
  28.     {
  29.       return GetKnownColors()
  30.           .Where(kvp => kvp.Value.Equals(color))
  31.           .Select(kvp => kvp.Key)
  32.           .FirstOrDefault();
  33.     }
  34.  
  35.     public static Color GetKnownColor(this string name)
  36.     {
  37.       Color color;
  38.       return GetKnownColors().TryGetValue(name, out color) ? color : Colors.Black; //if color for name is not found, return black
  39.     }
  40.  
  41.     #endregion
  42.  
  43.     public static Dictionary<string, Color> GetKnownColors()
  44.     {
  45.       if (knownColors == null)
  46.       {
  47.         var colorProperties = typeof(Colors).GetProperties(BindingFlags.Static | BindingFlags.Public);
  48.         knownColors = colorProperties.ToDictionary(
  49.           p => p.Name,
  50.           p => (Color)p.GetValue(null, null));
  51.       }
  52.       return knownColors;
  53.     }
  54.  
  55.     public static string[] GetKnownColorNames()
  56.     {
  57.       return GetKnownColors().Keys.ToArray();
  58.     }
  59.  
  60.     #endregion
  61.   }
  62. }

  1. No comments yet.
  1. No trackbacks yet.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.