Skip to content

Instantly share code, notes, and snippets.

@charliepark
Created July 18, 2010 12:03
Show Gist options
  • Save charliepark/480358 to your computer and use it in GitHub Desktop.
Save charliepark/480358 to your computer and use it in GitHub Desktop.
calculate contrast color in Ruby
def convert_to_brightness_value(background_hex_color)
(background_hex_color.scan(/../).map {|color| color.hex}).sum
end
def contrasting_text_color(background_hex_color)
convert_to_brightness_value(background_hex_color) > 382.5 ? '#000' : '#fff'
end
@utkarshrai003
Copy link

utkarshrai003 commented Jun 20, 2018

how is the 382.5 benchmark decided ? White has brightness value as 0, and for black, it comes as 510, so why not 510/2 = 255 ?

@neohunter
Copy link

FF FF FF is 255 255 255.

382.5 is (255*3) / 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment