Convert A XNA Color object to a string

混江龙づ霸主 提交于 2019-12-05 16:22:14
Bennor McCarthy

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.

var 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.

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