Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find most readable colour of text that is drawn on a coloured surface

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);
}
like image 217
Gautam Avatar asked Dec 23 '22 12:12

Gautam


2 Answers

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.

Color inverse(Color c)
{
    return new Color(c.R ^ 0x80, c.G ^ 0x80, c.B ^ 0x80);
}

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.

like image 180
George V. Reilly Avatar answered Feb 01 '23 23:02

George V. Reilly


The most readable color is going to be either white or black. The most 'soothing' color will be something that is not white nor black, it will be a color that lightly contrasts your background color. There is no way to programmatically do this because it is subjective. You will not find the most readable color for everyone because everyone sees things differently.

like image 24
user78071 Avatar answered Feb 01 '23 22:02

user78071