Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert color name to the corresponding hexadecimal representation?

For example:

blue 

converts to:

#0000FF

I wrote it as:

Color color = Color.FromName("blue");

But I don't know how to get the hexadecimal representation.

like image 512
Jack Avatar asked Dec 01 '11 04:12

Jack


People also ask

How do you represent a color in hexadecimal?

Hex color codes start with a pound sign or hashtag (#) and are followed by six letters and/or numbers. The first two letters/numbers refer to red, the next two refer to green, and the last two refer to blue. The color values are defined in values between 00 and FF (instead of from 0 to 255 in RGB).

What Colour is RGB 255 0 255?

To display black, set all color parameters to 0, like this: rgb(0, 0, 0). To display white, set all color parameters to 255, like this: rgb(255, 255, 255).

How do you convert RGB to hexadecimal?

RGB to hex conversion Convert the red, green and blue color values from decimal to hex. Concatenate the 3 hex values of the red, green and blue togather: RRGGBB.

How is the RGB decimal numbers related to its corresponding hex code?

RGB values are usually given in the 0–255 range; if they are in the 0–1 range, the values are multiplied by 255 before conversion. This number divided by sixteen (integer division; ignoring any remainder) gives the first hexadecimal digit (between 0 and F, where the letters A to F represent the numbers 10 to 15.


2 Answers

You're half way there. Use .ToArgb to convert it to it's numberical value, then format it as a hex value.

int ColorValue = Color.FromName("blue").ToArgb();
string ColorHex = string.Format("{0:x6}", ColorValue);
like image 186
Hand-E-Food Avatar answered Oct 13 '22 10:10

Hand-E-Food


var rgb = color.ToArgb() & 0xFFFFFF; // drop A component
var hexString = String.Format("#{0:X6}", rgb);

or just

var hexString = String.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
like image 28
Jim Balter Avatar answered Oct 13 '22 12:10

Jim Balter