Ideal font color

Tagged with Ruby

View as text

# simple example to illustrate how to use Ruby's math features
# to determine the font color based on a given
# background color.
def self.ideal_font_color_for(hex_str)
	hex_str = hex_str.split('#').last

	threshold = 105

	r = hex_str[0..1].hex
	g = hex_str[2..3].hex
	b = hex_str[4..5].hex

	delta = (r*0.299) + (g*0.587) + (b*0.114)

	255 - delta < threshold ? "#000000" : "#FFFFFF"
end
Last updated at 14:28 PM on Jul 07, 2008 by Brian Hogan

SnippetStash costs money to host and develop. The service is free for everyone to use
but if you found it useful please consider making a small donation.