Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to Color in C#

Tags:

c#

.net

xna

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?

I could think of using a switch statement and cases statement for each color type but I don't think that is clever enough.

like image 582
Kevin Avatar asked Aug 02 '10 20:08

Kevin


2 Answers

 Color red = Color.FromName("Red");   

The MSDN doesn't say one way or another, so there's a good chance that it is case-sensitive. (UPDATE: Apparently, it is not.)

As far as I can tell, ColorTranslator.FromHtml is also.

If Color.FromName cannot find a match, it returns new Color(0,0,0);

If ColorTranslator.FromHtml cannot find a match, it throws an exception.

UPDATE:

Since you're using Microsoft.Xna.Framework.Graphics.Color, this gets a bit tricky:

using XColor = Microsoft.Xna.Framework.Graphics.Color;
using CColor = System.Drawing.Color;

 CColor clrColor = CColor.FromName("Red"); 
 XColor xColor = new XColor(clrColor.R, clrColor.G, clrColor.B, clrColor.A);
like image 91
James Curran Avatar answered Nov 07 '22 16:11

James Curran


System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml("Red");

(Use my method if you want to accept HTML-style hex colors.)

like image 22
Larsenal Avatar answered Nov 07 '22 18:11

Larsenal