Skip to content

Instantly share code, notes, and snippets.

@juliarose
Created August 12, 2015 13:01
Show Gist options
  • Save juliarose/946a832e7b2adaa3e46d to your computer and use it in GitHub Desktop.
Save juliarose/946a832e7b2adaa3e46d to your computer and use it in GitHub Desktop.
Ruby color module - for blending two colors, lightening colors, and darkening colors.
module Color
def self.to_hex(c) # convert decimal to hex
n = c.to_i.to_s(16)
n = '0' + n unless n.length > 1 # 2 characters
n
end
def self.to_dec(c) # convert hex to decimal
c.to_i(16)
end
def self.blend(color1, color2, ratio = 0.5)
colors = 3.times.map do |i| # R, G, B
(to_dec(color2[i*2,2]) * ratio) + (to_dec(color1[i*2,2]) * (1-ratio))
end
colors.map { |a| to_hex(a) }.join
end
def self.lighten(color, ratio = 0.5)
colors = 3.times.map do |i| # R, G, B
[(to_dec(color[i*2,2]) + 255) * ratio,255].min
end
colors.map { |a| to_hex(a) }.join
end
def self.darken(color, ratio = 0.5)
ratio = 1.0 - ratio # inverse
colors = 3.times.map do |i| # R, G, B
to_dec(color[i*2,2]) * ratio
end
colors.map { |a| to_hex(a) }.join
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment