I know how to convert a string to an XNA Color
object, but how do I convert a C# Color
object like Color.Blue
into its string representation(e.g. "Blue").
views:
132answers:
3var color = System.Drawing.Color.Blue;
var known = color.ToKnownColor();
string name = known != null ? known.ToString() : "";
You will need to first convert the Microsoft.Xna.Framework.Graphics.Color into a System.Drawing.Color.
var color = System.Drawing.Color.FromArgb(a,r,g,b);
Then you get its name (if it has one) with the Name property.
You need to do the reverse of what was done in your previous question:
- Convert from XNA color to System color
- Try and convert the system color to a known color
- If the conversion worked, call ToString on the known color
e.g.
// Borrowed from previous question
using XnaColor = Microsoft.Xna.Framework.Graphics.Color;
System.Drawing.Color clrColor = System.Drawing.Color.FromName("Red");
XnaColor xnaColor = new XnaColor(clrColor.R, clrColor.G, clrColor.B, clrColor.A);
// Working back the other way
System.Drawing.Color newClrColor = System.Drawing.Color.FromArgb(xnaColor.A, xnaColor.R, xnaColor.G, xnaColor.B);
System.Drawing.KnownColor kColor = newClrColor.ToKnownColor();
string colorName = kColor != 0 ? kColor.ToString() : "";
Note: This will give you an empty string if the color name isn't known.
[EDIT] You might want to try using a TypeConverter here. I'm not sure that one exists for the XNA Color type, but it's worth a shot:
string colorName = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Microsoft.Xna.Framework.Graphics.Color)).ConvertToString(yourXnaColor);
[EDIT]
Since none of the above is going to do what you want, you'll have to try a similar approach to what Jon has done here: http://stackoverflow.com/questions/3391462/convert-string-to-color-in-c/3391583#3391583
You'll need to pull all the XNA colors into a dictionary using reflection, like he has done, but reverse the keys and values, so it's Dictionary, then write a function that accesses the dictionary taking a Color parameter and returning the name.