The Dev Blog

Putting Family Management on Rails!

Finding Good Color Contrast

Posted by Guy Naor Wed, 14 Jun 2006 14:20:00 GMT

Giving our Famundo users the ability to change some background colors on the header to match the logo, brough up the problem of selecting the correct color to use for text we have to write on the header. We can't default to just a specific color as it might not be readable on some of the colors.

The W3C recommends how to select colors to achieve good readability. It's a nice formula to find the color contrast and brightness difference. They also recommend on a treshold to compare against, when selecting the colors. I wrote ruby code to do that calculation. You can change the tresholds to give you more latitute in selecting colors.

# Return true if the difference between two colors 
# matches the W3C recommendations for readability
# See http://www.wat-c.org/tools/CCA/1.1/
def colors_diff_ok? c1, c2
  cont, bright = find_color_diff c1, c2
  (cont > 500) && (bright > 125) # Acceptable diff according to w3c
end

# Return the contranst and brightness difference between two RGB values
def find_color_diff c1, c2
  r1, g1, b1 = break_color c1
  r2, g2, b2 = break_color c2
  cont_diff = (r1-r2).abs+(g1-g2).abs+(b1-b2).abs # Color contrast
  bright1 = (r1 * 299 + g1 * 587 + b1 * 114) / 1000
  bright2 = (r2 * 299 + g2 * 587 + b2 * 114) / 1000
  brt_diff = (bright1 - bright2).abs # Color brightness diff
  [cont_diff, brt_diff]
end

# Break a color into the R, G and B components    
def break_color rgb
  r = (rgb & 0xff0000) >> 16
  g = (rgb & 0x00ff00) >> 8
  b = rgb & 0x0000ff
  [r,g,b] 
end

A simple way to use it, is to have an array with different color options, and look in it for a match:

possible_colors = [0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0x00ffff, 0xffffff]
good_color = 0 # We can default to black...
possible_colors.each do |c|
  if colors_diff_ok? c, my_color
    good_color = c
    break
  end
end

Posted in  | no comments | no trackbacks

del.icio.us:Finding Good Color Contrast digg:Finding Good Color Contrast spurl:Finding Good Color Contrast wists:Finding Good Color Contrast simpy:Finding Good Color Contrast newsvine:Finding Good Color Contrast blinklist:Finding Good Color Contrast furl:Finding Good Color Contrast reddit:Finding Good Color Contrast fark:Finding Good Color Contrast blogmarks:Finding Good Color Contrast Y!:Finding Good Color Contrast smarking:Finding Good Color Contrast magnolia:Finding Good Color Contrast segnalo:Finding Good Color Contrast

Comments

Trackbacks

Use the following link to trackback from your own site:
http://devblog.famundo.com/articles/trackback/18

Comments are disabled

Subscribe to The Dev Blog