I am encountering a problem which is how do I convert input strings like \"RED\" to the actual Color type Color.Red
in C#. Is there a good way to do this?
It depends on what you're looking for, if you need System.Windows.Media.Color (like in WPF) it's very easy:
System.Windows.Media.Color color = (Color)System.Windows.Media.ColorConverter.ConvertFromString("Red");//or hexadecimal color, e.g. #131A84
Since the OP mentioned in a comment that he's using Microsoft.Xna.Framework.Graphics.Color
rather than System.Drawing.Color
you can first create a System.Drawing.Color then convert it to a Microsoft.Xna.Framework.Graphics.Color
public static Color FromName(string colorName)
{
System.Drawing.Color systemColor = System.Drawing.Color.FromName(colorName);
return new Color(systemColor.R, systemColor.G, systemColor.B, systemColor.A); //Here Color is Microsoft.Xna.Framework.Graphics.Color
}
The following can generate a color from name, hex, or known name.
Color beige = StringToColor("Beige");
Color purple = StringToColor("#800080");
Color window = StringToColor("Window");
public static Color StringToColor(string colorStr)
{
TypeConverter cc = TypeDescriptor.GetConverter(typeof(Color));
var result = (Color)cc.ConvertFromString(colorStr);
return result;
}
The snippet was taken from Jo Albahari's C# in a Nutshell.
System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml("Red");
(Use my method if you want to accept HTML-style hex colors.)