开发者

C# Create Instance of Color from any supported Format (Win.Forms Properties -> Color)

开发者 https://www.devze.com 2023-01-05 17:20 出处:网络
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

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 th开发者_Python百科is "FF00FF11" from this "Gray"?

Any help will be appreciated.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号