Convert string to Color in C#

后端 未结 10 1409
我寻月下人不归
我寻月下人不归 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: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.

提交回复
热议问题