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.
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).
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).
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.
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With