Calculating Color Contrast for Legible Text in Ruby

Back in 2008, Kevin Hale (at Wufoo) published Calculating Color Contrast for Legible Text. In it, he goes over how to determine the best contrasting color (that is, either pure white or pure black) when given a random hexadecimal color (something like “#851B03”).

For example, that “#851B03” with black text looks like this:

#851B03

With white text, it looks better. Like this:

#851B03

When it’s a one-off color, it’s not hard to see whether white text or black text gives a higher contrast (and easier legibility). But how do you determine the color when the background color is provided randomly?

Kevin’s post showed how to handle it with PHP. Since I’m using Ruby to build the web-based component of Monotask, I had to take their PHP implementation and map it out in Ruby. I thought I’d share what I came up with.

Basically, you give it a hexadecimal color code, like the #851B03 we used before. (Note: don’t pass along the “#” … just “851B03”.) The first method splits the color up into its three components (red: 85; green: 1B; blue: 03), then converts each of those numbers into an integer between 0 and 255 (red:133; green:27; blue 3). Then, it adds those three numbers up (163).

The second method takes that value and compares it with the exact halfway-point between pure black (0 + 0 + 0 = 0) and pure white (255 + 255 + 255 = 765), which comes out to 382.5. If the value the first method spits out is less than 382.5, the original color is closer to black (it’s a darker color), so the contrasting color should be white. Greater than 382.5, the original color is closer to white, and the contrasting color should be black.

In our example, “851B03” converts to a brightness value of 163. Since that’s less than 382.5, it’s a dark color, and the more legible text color is going to be white. (As we saw above.)

When you stick these two methods into your app’s helper methods, you can quickly determine the contrasting color for any hexadecimal color value on the fly. You’ll be able to see it in use, before too long, in Monotask, looking something like this:

(Ignore the names of the working states, and the duplicates. But note how “writing”, “research”, and the blue “Inbox Zero” at the bottom of the list all have lighter background colors and have black text, where the other ones are darker colors, and so have white text.)

Sunday, July 18, 2010 — 12 notes
  1. egimenez reblogged this from charliepark
  2. charliepark posted this