Click here to Skip to main content
15,868,141 members
Articles / Programming Languages / C#
Tip/Trick

Calculating Textcolor Contrast

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
6 Feb 2011CPOL 15K   4   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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Switzerland Switzerland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralFixed the link. Pin
Steve Maier3-Feb-11 8:09
professionalSteve Maier3-Feb-11 8:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.