user954469
user954469

Reputation: 1103

Algorithm to get best text color

I'm looking for an algorithm to get the best text color (most pleasing to the eye) from a given background color.

Any idea ?

Upvotes: 8

Views: 1130

Answers (2)

Konrad Garus
Konrad Garus

Reputation: 54005

"The best color" is very subjective and context dependent. It depends on what effect you want: If you want the highest contrast possible, look for complementary colors (that would give you red on green, yellow on blue etc.). If you want colors that are "similar", look for analogous harmonies. If you want to decide between black and white only, measure brightness (hamstergene posted a very good formula for it).

Wherever you go, HSV color model is the key.

Getting complementary or analogous colors is trivial (e.g. hue_text = (hue_bg + 180) % 360 OR hue_text = (hue_bg + 30) % 360).

You can also experiment with value (lightness) and saturation for better contrast. For example, v_text = 1 - v_bg could give you dark text on bright background and vice versa (watch out for mid tones!). It doesn't have to be linear - you also could go for a step function like: if v_bg < 0.5 then v_text = 1 else v_text = 0, or if s_bg < 0.5 then s_text = 1 else s_text = 0 (vibrant on pale).

That's just some hints. In a word: It depends!

Google for color theory and color harmonies. Some links:

http://www.tigercolor.com/color-lab/color-theory/color-harmonies.htm

http://www.colormatters.com/color-and-design/basic-color-theory

Upvotes: 12

hamstergene
hamstergene

Reputation: 24429

There is no best for everyone.

Say if you need to make sure text will be easily readable, the following simple formula worked well for me:

textColor = brightness(backColor) > 0.5 ? black : white;

where brightness is defined as

brightness(R,G,B) = 0.299*R + 0.587*G + 0.114*B

(there are several definitions for “brightness”, I used this one but I think any one would work).

Upvotes: 6

Related Questions