I’m not sure how to ask this but here goes.
I draw a filled coloured rectangle on screen. The colour is in form of R,G,B
I then want to draw text on top of the rectangle, however the colour of the text has to be such that it provides the best contrast, meaning it’s readable.
Example:
If I draw a black rectangle, the obvious colour for text would be white.
What I tried right now is this. I pass this function the colour of the rectangle and it returns an inverted colour that I then use for my text.
It works, but it’s not the best way.
Any suggestions?
// eg. usage: Color textColor = GetInverseLuminance(rectColor); private Color GetInverseLuminance(Color color) { int greyscale = (int)(255 - ((color.R * 0.30f) + (color.G * 0.59f) + (color.B * 0.11f))); return Color.FromArgb(greyscale, greyscale, greyscale); }
One simple approach that is guaranteed to give a significantly different color is to toggle the top bit of each component of the RGB triple.
If the original color was #1AF283, the ‘inverse’ will be #9A7203.
The contrast will be significant. I make no guarantees about the aesthetics.
Update, 2009/4/3: I experimented with this and other schemes. Results at my blog.