Created
March 14, 2015 18:48
-
-
Save kascote/4bd4893cab46b3b6a770 to your computer and use it in GitHub Desktop.
Calculate Lighter or Darker Hex Colors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Examples: | |
# color_luminance("#69c", 0); # returns "#6699cc" | |
# color_luminance("6699CC", 0.2); # "#7ab8f5" - 20% lighter | |
# color_luminance("69C", -0.5); # "#334d66" - 50% darker | |
# color_luminance("000", 1); # "#000000" - true black cannot be made lighter! | |
# | |
# based on code from | |
# http://www.sitepoint.com/javascript-generate-lighter-darker-color/ | |
# | |
def color_luminance(hex, lum) | |
color = hex.strip.match(/\A#?([0-9a-f]*)\z/i) | |
return hex if color.nil? | |
color = color[1] | |
if color.length < 6 | |
color = color[0] + color[0] + color[1] + color[1] +color[2] + color[2] | |
end | |
rgb = '#' | |
(0..2).each do |i| | |
x = Integer(color.slice(i*2,2), 16).to_s(10).to_i | |
x = Integer([[0,x+(x*lum)].max,255].min.round.to_s, 10).to_s(16) | |
rgb << ('00'+x)[x.length..-1] | |
end | |
return rgb | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment