.net 如何从十六进制 RGB 字符串创建 System.Drawing.Color?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1914487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a System.Drawing.Color from its hexadecimal RGB string?
提问by Jader Dias
I want to create a System.Drawing.Colorfrom a value like #FF00FFor FF00FFwithout needing to write code for that. There is any .NET built-in parser for that?
我想System.Drawing.Color从一个类似#FF00FF或FF00FF不需要为此编写代码的值创建一个。有任何 .NET 内置解析器吗?
回答by Jo?o Angelo
ColorTranslator.FromHtml("#FF00FF");
回答by Pat
You can use the System.Drawing.ColorTranslator static method FromHtml.
您可以使用 System.Drawing.ColorTranslator 静态方法 FromHtml。
use:
用:
System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
回答by Bobby
It is rather easy when you use the Convert-Class. The ToInt32function has an overload with a second parameter which represents the base the string is in.
使用Convert-Class时相当容易。该ToInt32函数有一个带有第二个参数的重载,该参数表示字符串所在的基数。
using System.Drawing
Color yourColor = Color.FromARGB(Convert.ToInt32("FF00FF", 16));
回答by Phil Devaney
Use the ColorConverterclass:
使用ColorConverter类:
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" )
这也可以从标准命名颜色转换,例如 ConvertFromString( "Blue" )
See herefor a discussion of the standard .NET type conversion mechanisms.
有关标准 .NET 类型转换机制的讨论,请参见此处。
回答by Michael Rodby
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.FromNameor System.Drawing.Color.FromHtml, since the parsing from a string to integer is done at compile time rather than at runtime.
如果要使用的颜色是常量,请在 C# 中使用System.Drawing.Color.FromArgb (0xFF00FF). 这比System.Drawing.Color.FromNameor稍快System.Drawing.Color.FromHtml,因为从字符串到整数的解析是在编译时完成的,而不是在运行时完成。
回答by bicbmx
The FromName method worked for me
FromName 方法对我有用
System.Drawing.Color.FromName("#FF00FF");

