How to create a System.Drawing.Color from its hexa

2019-01-18 00:47发布

I want to create a System.Drawing.Color from a value like #FF00FF or FF00FF without needing to write code for that. There is any .NET built-in parser for that?

6条回答
Anthone
2楼-- · 2019-01-18 01:28

The FromName method worked for me

System.Drawing.Color.FromName("#FF00FF");
查看更多
爷的心禁止访问
3楼-- · 2019-01-18 01:33

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

use:

System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
查看更多
不美不萌又怎样
4楼-- · 2019-01-18 01:33

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));
查看更多
祖国的老花朵
5楼-- · 2019-01-18 01:34

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.

查看更多
叼着烟拽天下
6楼-- · 2019-01-18 01:37

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.

查看更多
甜甜的少女心
7楼-- · 2019-01-18 01:51
ColorTranslator.FromHtml("#FF00FF");
查看更多
登录 后发表回答