Module: ColorHelpers::ActionViewExtension

Defined in:
lib/color_helpers/helpers.rb

Instance Method Summary collapse

Instance Method Details

#color_to_grayscale(hex_color) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/color_helpers/helpers.rb', line 42

def color_to_grayscale(hex_color)
  hex_color = hex_color.gsub('#','')
  rgb = hex_color.scan(/../).map(&:hex)
  grayscale_factors = {r: 0.21, g: 0.72, b: 0.07}
  rgb[0] = (rgb[0].to_i * grayscale_factors[:r] + rgb[1].to_i * grayscale_factors[:g] + rgb[2].to_i * grayscale_factors[:b]).round
  rgb[1] = rgb[2] = rgb[0]
  "#%02x%02x%02x" % rgb
end

#contrasting_text_color(hex_color, options = {}) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/color_helpers/helpers.rb', line 29

def contrasting_text_color(hex_color, options = {})
  color = hex_color.gsub('#','')
  if options[:monochrome] == true
    convert_to_brightness_value(color) > 382.5 ? "#000000" : "#ffffff"
  else
    convert_to_brightness_value(color) > 382.5 ? darken_color(color) : lighten_color(color)
  end
end

#convert_to_brightness_value(hex_color) ⇒ Object



38
39
40
# File 'lib/color_helpers/helpers.rb', line 38

def convert_to_brightness_value(hex_color)
   (hex_color.scan(/../).map {|color| color.hex}).sum
end

#darken_color(hex_color, amount = 0.4) ⇒ Object



17
18
19
20
21
# File 'lib/color_helpers/helpers.rb', line 17

def darken_color(hex_color, amount=0.4)
  hex_color = hex_color.gsub('#','')
  rgb = hex_color.scan(/../).map(&:hex).map{|color| color * amount}.map(&:round)
  "#%02x%02x%02x" % rgb
end

#hex_to_rgb(hex_color) ⇒ Object



7
8
9
10
# File 'lib/color_helpers/helpers.rb', line 7

def hex_to_rgb(hex_color)
  color = hex_color.gsub('#','')
  "rgb("+color.scan(/../).map {|color| color.to_i(16)}.join(",").to_s+")"
end

#lighten_color(hex_color, amount = 0.6) ⇒ Object



23
24
25
26
27
# File 'lib/color_helpers/helpers.rb', line 23

def lighten_color(hex_color, amount=0.6)
  hex_color = hex_color.gsub('#','')
  rgb = hex_color.scan(/../).map(&:hex).map{|color| (color + 255) * amount}.map{|color| [color.round, 255].min}
  "#%02x%02x%02x" % rgb
end

#random_hex_colorObject



3
4
5
# File 'lib/color_helpers/helpers.rb', line 3

def random_hex_color
  "#"+SecureRandom.hex(3)
end

#rgb_to_hex(rgb_color) ⇒ Object



12
13
14
15
# File 'lib/color_helpers/helpers.rb', line 12

def rgb_to_hex(rgb_color)
  color =  rgb_color.delete("rgb() ").split(",")
  "#%02x%02x%02x" % color
end