In C# , How can i create a System.Drawing.Color object using a value like this #FFFFF,#FGFG01 etc...
Asked
Active
Viewed 1.8k times
18
-
Be aware if you are getting the hex value from the querystring, the hash will be URL encoded as %23. – Phillip Jan 18 '13 at 06:37
4 Answers
32
string hexValue = "#000000"; // You do need the hash
Color colour = System.Drawing.ColorTranslator.FromHtml(hexValue); // Yippee
Edit: You do actually need the hash, or the alpha value won't be taken into account. Woops!

djdd87
- 67,346
- 27
- 156
- 195
-
1
-
Had to change my if (color == Black) comparison as they're two different objects, so the condition would never have been true. Kept the yippee comment in - just for you! – djdd87 Nov 19 '09 at 10:52
-
3
var my col = Color.FromArgb(int x);
note you need to specify an alpha value as well (probably you want FF for this, i.e. fully opaque, so add 0xFF000000 to the colour hex value)

jk.
- 13,817
- 5
- 37
- 50
-
+1 He can use Int32.Parse to turn a hex string into an int, just drop the #. – Matt Ellen Nov 19 '09 at 10:38
1
Can you change the values to start with FF? E.g. FFFFFFFF = white. This is to add the alpha value to the beginning.
If so, just parse the value with System.Drawing.Color.FromArgb
. It takes an int
where the first 8 bits are the alpha value. 255 is opaque.
To convert your string into an int, use Int32.Parse. E.g.
String HexColourValue = "FABFAB";
System.Drawing.Color colour = System.Drawing.Color.FromArgb(Int32.Parse("FF"+HexColourValue,
System.Globalization.NumberStyles.HexNumber));
Make sure that HexColourValue
doesn't have '#' in it.

Matt Ellen
- 11,268
- 4
- 68
- 90
0
Color.FromArgb(Convert.ToInt32( str.Substring(1), 16 ));

EricSchaefer
- 25,272
- 21
- 67
- 103
-
-
Yes, it does, if alpha is supported. You would have to use #FF123456 if you want nontransparent colors or add 0xff000000 to the conversion result. – EricSchaefer Nov 19 '09 at 13:33