如何根据其十六进制 RGB 字符串创建 System.Drawing.Color?

我想创建一个类似于 #FF00FFFF00FF的值的 System.Drawing.Color,而不需要为此编写代码。有的。NET 内置的解析器吗?

96987 次浏览

It is rather easy when you use the Convert-Class. The ToInt32 function has an overload with a second parameter which represents the base the string is in.

using System.Drawing


Color yourColor = Color.FromARGB(Convert.ToInt32("FF00FF", 16));

Use the ColorConverter class:

var converter = System.ComponentModel.TypeDescriptor.GetConverter( typeof( Color ) );
color = converter.ConvertFromString( "#FF00FF" );

This can also convert from the standard named colors e.g. ConvertFromString( "Blue" )

See here for a discussion of the standard .NET type conversion mechanisms.

ColorTranslator.FromHtml("#FF00FF");

You can use the System.Drawing.ColorTranslator static method FromHtml.

use:

System.Drawing.ColorTranslator.FromHtml("#FFFFFF");

The FromName method worked for me

System.Drawing.Color.FromName("#FF00FF");

If the color you want to use is a constant, in C# use System.Drawing.Color.FromArgb (0xFF00FF). That is slightly faster than System.Drawing.Color.FromName or System.Drawing.Color.FromHtml, since the parsing from a string to integer is done at compile time rather than at runtime.