How to pick good contrast RGB colors programmatically?

James Raitsev picture James Raitsev · Aug 31, 2011 · Viewed 12.1k times · Source

Suppose, in your program:

  1. color A is a color we randomly select

  2. Knowing color A, how can I pick a color B that will be in high contrast with color A?

The problem can be further reduced to: "imagine 2 squares filled with color next to one another. It should be unambiguously clear to a human eye that colors are not the same"

Example:

  • Black --> White
  • Blue --> White

Answer

woliveirajr picture woliveirajr · Aug 31, 2011

There is some information in the Web Content Accessibility Guidelines (WCAG) 2.0 (http://www.w3.org/TR/2008/REC-WCAG20-20081211)

  1. Visual contrast: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast

  2. Contrast ratio: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef

  3. Relative luminance : http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef

There's a good example in this site but he calculate where two colors are enough, not how to get them.

To choose a color with good contrast, I'd go with complementary colors: for example, choose the random color A, transform it to a HSV space, get the complementary hue.

Complementary hue: after you transform color from RGB to HSV, complementary hue will be 180 degrees appart (or 0.5, in a 0-1 normalized hue value). This site has something about it in PHP