将字符串转换为彩色在C# [英] Convert string to Color in C#
问题描述
一个我遇到一个问题,就是如何转换输入的字符串,如红在C#中的实际颜色类型 Color.Red
。有没有好的办法做到这一点?
我能想到用switch语句和案例的语句每种颜色类型,但我不认为这是不够聪明。
颜色红= Color.FromName(红楼梦);
在MSDN没有说这样或那样的,所以这是一个很好的机会,这是区分大小写的。 (更新:显然,这是不)
据我所知, ColorTranslator.FromHtml
是也。
如果 Color.FromName
找不到匹配,则返回新颜色(0,0,0);
如果 ColorTranslator.FromHtml
无法找到匹配,它抛出一个异常。
更新:
由于您使用Microsoft.Xna.Framework.Graphics.Color,这变得有点棘手:
使用XColor = Microsoft.Xna.Framework.Graphics.Color;
使用CColor =的System.Drawing.Color;
CColor clrColor = CColor.FromName(红楼梦);
XColor xColor =新XColor(clrColor.R,clrColor.G,clrColor.B,clrColor.A);
A 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?
I could think of using a switch statement and cases statement for each color type but I don't think that is clever enough.
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);
这篇关于将字符串转换为彩色在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!