Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lipowen/e1943e1f3f63ef89fa8f8dc8caff829e to your computer and use it in GitHub Desktop.
Save lipowen/e1943e1f3f63ef89fa8f8dc8caff829e to your computer and use it in GitHub Desktop.
Lighten or darken a hexadecimal color (string)
# Amount should be a decimal between 0 and 1. Lower means darker
def darken_color(hex_color, amount=0.4)
hex_color = hex_color.gsub('#','')
rgb = hex_color.scan(/../).map {|color| color.hex}
rgb[0] = (rgb[0].to_i * amount).round
rgb[1] = (rgb[1].to_i * amount).round
rgb[2] = (rgb[2].to_i * amount).round
"#%02x%02x%02x" % rgb
end
# Amount should be a decimal between 0 and 1. Higher means lighter
def lighten_color(hex_color, amount=0.6)
hex_color = hex_color.gsub('#','')
rgb = hex_color.scan(/../).map {|color| color.hex}
rgb[0] = [(rgb[0].to_i + 255 * amount).round, 255].min
rgb[1] = [(rgb[1].to_i + 255 * amount).round, 255].min
rgb[2] = [(rgb[2].to_i + 255 * amount).round, 255].min
"#%02x%02x%02x" % rgb
end
@lipowen
Copy link
Author

lipowen commented Apr 16, 2020

def opacity(hex_color, amount = 0.5)
  hex_color = hex_color.gsub('#', '')
  rgb = hex_color.scan(/../).map { |color| color.hex }
  rgb = rgb.map { |color| [(color.to_i * amount + 255 * (1 - amount)).round, 255].min }

  "#%02x%02x%02x" % rgb
end

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