Convert string to Color in C#

后端 未结 10 952
我寻月下人不归
我寻月下人不归 2020-11-29 07:03

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?

相关标签:
10条回答
  • 2020-11-29 07:47

    It depends on what you're looking for, if you need System.Windows.Media.Color (like in WPF) it's very easy:

    System.Windows.Media.Color color = (Color)System.Windows.Media.ColorConverter.ConvertFromString("Red");//or hexadecimal color, e.g. #131A84
    
    0 讨论(0)
  • 2020-11-29 07:48

    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
    }
    
    0 讨论(0)
  • 2020-11-29 07:49

    The following can generate a color from name, hex, or known name.

    Color beige = StringToColor("Beige");
    Color purple = StringToColor("#800080");
    Color window = StringToColor("Window");
    
    public static Color StringToColor(string colorStr)
    {
        TypeConverter cc = TypeDescriptor.GetConverter(typeof(Color));
        var result = (Color)cc.ConvertFromString(colorStr);
        return result;
    }
    

    The snippet was taken from Jo Albahari's C# in a Nutshell.

    0 讨论(0)
  • 2020-11-29 07:50
    System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml("Red");
    

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

    0 讨论(0)
提交回复
热议问题