Skip to content

Instantly share code, notes, and snippets.

@polarblau
Created November 3, 2012 21:30
Show Gist options
  • Save polarblau/4008920 to your computer and use it in GitHub Desktop.
Save polarblau/4008920 to your computer and use it in GitHub Desktop.
Ruby color helpers
# http://24ways.org/2010/calculating-color-contrast
def contrast_color(hex_color, dark_option, bright_option)
rgb = hex_to_rgb(hex_color)
yiq = luminance(*rgb) / 1000
yiq >= 128 ? dark_option : bright_option
end
def hex_to_rgb(hex_color)
hex_color = hex_color.gsub(%r{[#;]}, '')
case hex_color.size
when 3
hex_color.scan(%r{[0-9A-Fa-f]}).map { |el| (el * 2).to_i(16) }
when 6
hex_color.scan(%r<[0-9A-Fa-f]{2}>).map { |el| el.to_i(16) }
else
raise ArgumentError
end
end
def rgb_to_hex(r, g, b)
r = r.round
r = 255 if r > 255
g = g.round
g = 255 if g > 255
b = b.round
b = 255 if b > 255
"#%02x%02x%02x" % [r, g, b]
end
def luminance(r, g, b)
r * 299 + g * 587 + b * 114
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment