Kevin
Kevin

Reputation: 6831

Convert A XNA Color object to a string

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").

Upvotes: 4

Views: 2062

Answers (3)

Bennor McCarthy
Bennor McCarthy

Reputation: 11675

You need to do the reverse of what was done in your previous question:

  1. Convert from XNA color to System color
  2. Try and convert the system color to a known color
  3. 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: Convert string to Color in C#

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.

Upvotes: 3

Struan
Struan

Reputation: 655

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.

Upvotes: 1

John Fisher
John Fisher

Reputation: 22719

var color = System.Drawing.Color.Blue;
var known = color.ToKnownColor();
string name = known != null ? known.ToString() : "";

Upvotes: 3

Related Questions