Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Calculating Textcolor Contrast

0.00/5 (No votes)
6 Feb 2011 1  
How to finde maximum Contrast of a Webcolor
The simple snippets of code calculates the text color (contrast) of a background color.

C#
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[^].

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here