Convert string to Color in C#

2020-01-26 08:20发布

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.

标签: c# .net xna
9条回答
混吃等死
2楼-- · 2020-01-26 08:59
System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml("Red");

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

查看更多
3楼-- · 2020-01-26 09:01

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
}
查看更多
相关推荐>>
4楼-- · 2020-01-26 09:01

For transferring colors via xml-strings I've found out:

Color x = Color.Red; // for example
String s = x.ToArgb().ToString()
... to/from xml ...
Int32 argb = Convert.ToInt32(s);
Color red = Color.FromArgb(argb);
查看更多
登录 后发表回答