Convert string to Color in C#

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

    The simplest way:

    string input = null;
    Color color = Color.White;
    
    TextBoxText_Changed(object sender, EventsArgs e)
    {
       input = TextBox.Text;
    }
    
    Button_Click(object sender, EventsArgs e)
    {
       color = Color.FromName(input)
    }
    
    0 讨论(0)
  • 2020-11-29 07:31

    I've used something like this before:

            public static T CreateFromString<T>(string stringToCreateFrom) {
    
            T output = Activator.CreateInstance<T>();
    
            if (!output.GetType().IsEnum)
                throw new IllegalTypeException();
    
            try {
                output = (T) Enum.Parse(typeof (T), stringToCreateFrom, true);
            }
            catch (Exception ex) {
                string error = "Cannot parse '" + stringToCreateFrom + "' to enum '" + typeof (T).FullName + "'";
                _logger.Error(error, ex);
                throw new IllegalArgumentException(error, ex);
            }
    
            return output;
        }
    
    0 讨论(0)
  • 2020-11-29 07:34

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

    This worked nicely for my needs ;) Hope someone can use it....

        public static Color FromName(String name)
        {
            var color_props= typeof(Colors).GetProperties();
            foreach (var c in color_props)
                if (name.Equals(c.Name, StringComparison.OrdinalIgnoreCase))
                    return (Color)c.GetValue(new Color(), null);
            return Colors.Transparent;
        }
    
    0 讨论(0)
  • 2020-11-29 07:40
     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);
    
    0 讨论(0)
  • 2020-11-29 07:44

    (It would really have been nice if you'd mentioned which Color type you were interested in to start with...)

    One simple way of doing this is to just build up a dictionary via reflection:

    public static class Colors
    {
        private static readonly Dictionary<string, Color> dictionary =
            typeof(Color).GetProperties(BindingFlags.Public | 
                                        BindingFlags.Static)
                         .Where(prop => prop.PropertyType == typeof(Color))
                         .ToDictionary(prop => prop.Name,
                                       prop => (Color) prop.GetValue(null, null)));
    
        public static Color FromName(string name)
        {
            // Adjust behaviour for lookup failure etc
            return dictionary[name];
        }
    }
    

    That will be relatively slow for the first lookup (while it uses reflection to find all the properties) but should be very quick after that.

    If you want it to be case-insensitive, you can pass in something like StringComparer.OrdinalIgnoreCase as an extra argument in the ToDictionary call. You can easily add TryParse etc methods should you wish.

    Of course, if you only need this in one place, don't bother with a separate class etc :)

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