Convert string to Color in C#

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

提交回复
热议问题