How to convert Hex to RGB?

You can use:

public string GenerateRgba(string backgroundColor, decimal backgroundOpacity)
{
 Color color = ColorTranslator.FromHtml(hexBackgroundColor);
 int r = Convert.ToInt16(color.R);
 int g = Convert.ToInt16(color.G);
 int b = Convert.ToInt16(color.B);
 return string.Format("rgba({0}, {1}, {2}, {3});", r, g, b, backgroundOpacity);
}

Link To original Post by jeremy clifton on git


I am trying to use this to figure out if a color is light or dark

Just use Color.GetBrightness()


[Edit]

I want to determine if I should use white or black for my text. So anything ≤ .5 I should use white and > .5 black?

There are a number of ways to determine what color to use on a given background, none of which are perfect.

That last link actually recommends using black/white only, but choosing a cutoff point of 0.73 instead of 0.5. I think you should just go with that, and change it if you find it doesn't work for you.


Just convert the hex string to an integer:

int color = Convert.ToInt32("FFFFFF", 16);

Tags:

C#

.Net

Hex

Colors

Rgb