tags:

views:

29

answers:

2

Hello

What is the best way to instantiate a new Color from any supported value, like for example "FF00FF11" or "Gray" or "234,255,65"? I need to generalize maximum as possible this implementation, but can't find a way to do it.

With System.Reflaction I can get the value for enumerator KnownColor, but how can I distinct this "FF00FF11" from this "Gray"?

Any help will be appreciated.

A: 

You might want to take a look at System.Drawing.ColorTranslator.FromHtml(string).

I'm not sure it'll help you with your last example ("234,255,65"), however. You might have to try to parse that first (String.Split(), Int32.TryParse(), Color.FromArgb()) and if it fails, use the above.

lc
+1  A: 

When we need to do this we used the TypeConverter. The static function I used was:

    private static System.ComponentModel.TypeConverter colorConv = System.ComponentModel.TypeDescriptor.GetConverter(System.Drawing.Color.Red);

    /// <summary>
    /// Parse a string to a Color
    /// </summary>
    /// <param name="txt"></param>
    /// <returns></returns>
    public static System.Drawing.Color ColorFromString(string txt)
    {
        try
        {
            object tmp = colorConv.ConvertFromString(txt);
            return (tmp is System.Drawing.Color) ? (System.Drawing.Color)tmp : System.Drawing.Color.Empty;
        }
        catch 
        {
            // Failed To Parse String
            return System.Drawing.Color.Empty;
        }
    }

This works for two of your cases but fails on the Hex one. You could add some logic to try to parse the Hex one first.

JDunkerley