65.9K
CodeProject is changing. Read more.
Home

Calculating Textcolor Contrast

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Feb 3, 2011

CPOL
viewsIcon

15508

How to finde maximum Contrast of a Webcolor

The simple snippets of code calculates the text color (contrast) of a background color.
string getContrast(string hexcolor)
{
int r = Convert.ToInt32("0x"+hexcolor.Substring(0,2), 16);
int g = Convert.ToInt32("0x"+hexcolor.Substring(2,2), 16);
int b = Convert.ToInt32("0x"+hexcolor.Substring(4,2), 16);
int yiq = ((r*299)+(g*587)+(b*114))/1000;
if(yiq >= 131.5)
return "black";
else
return "white";
}
The code is based on the following Blogentry: http://24ways.org/2010/calculating-color-contrast[^].