How to create a System.Drawing.Color from its hexadecimal RGB string?

.NetColorsParsingHexsystem.drawing.color

.Net Problem Overview


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?

.Net Solutions


Solution 1 - .Net

ColorTranslator.FromHtml("#FF00FF");

Solution 2 - .Net

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

use:

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

Solution 3 - .Net

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));

Solution 4 - .Net

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.

Solution 5 - .Net

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.

Solution 6 - .Net

The FromName method worked for me

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJader DiasView Question on Stackoverflow
Solution 1 - .NetJoão AngeloView Answer on Stackoverflow
Solution 2 - .NetPatView Answer on Stackoverflow
Solution 3 - .NetBobbyView Answer on Stackoverflow
Solution 4 - .NetPhil DevaneyView Answer on Stackoverflow
Solution 5 - .NetMichael RodbyView Answer on Stackoverflow
Solution 6 - .NetbicbmxView Answer on Stackoverflow