Class: Cheers::Color
- Inherits:
-
Object
- Object
- Cheers::Color
- Defined in:
- lib/cheers/color.rb
Overview
Represents a color and allows to compare to others (maybe)
Instance Attribute Summary collapse
-
#b ⇒ Object
Returns the value of attribute b.
-
#g ⇒ Object
Returns the value of attribute g.
-
#r ⇒ Object
Returns the value of attribute r.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(color = '#000000') ⇒ Color
constructor
Create new color from a hex value.
- #similar?(other_color, threshold = 0.1) ⇒ Boolean
- #to_hsv ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(color = '#000000') ⇒ Color
Create new color from a hex value
8 9 10 11 12 13 |
# File 'lib/cheers/color.rb', line 8 def initialize(color = '#000000') hex_string = color[1..6] self.r = hex_string[0..1].to_i(16) self.g = hex_string[2..3].to_i(16) self.b = hex_string[4..5].to_i(16) end |
Instance Attribute Details
#b ⇒ Object
Returns the value of attribute b.
5 6 7 |
# File 'lib/cheers/color.rb', line 5 def b @b end |
#g ⇒ Object
Returns the value of attribute g.
5 6 7 |
# File 'lib/cheers/color.rb', line 5 def g @g end |
#r ⇒ Object
Returns the value of attribute r.
5 6 7 |
# File 'lib/cheers/color.rb', line 5 def r @r end |
Class Method Details
.rgb_to_hex(rgb) ⇒ Object
58 59 60 61 |
# File 'lib/cheers/color.rb', line 58 def self.rgb_to_hex(rgb) hex = rgb.map {|c| c.to_s(16).rjust(2, '0')}.join return "##{hex}" end |
Instance Method Details
#similar?(other_color, threshold = 0.1) ⇒ Boolean
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/cheers/color.rb', line 41 def similar?(other_color, threshold = 0.1) other_color = Color.new(other_color) unless other_color.is_a? Color color_hsv = to_hsv other_color_hsv = other_color.to_hsv d_hue = (color_hsv[0] - other_color_hsv[0]).abs / 360 d_saturation = (color_hsv[1] - other_color_hsv[1]).abs d_value = (color_hsv[2] - other_color_hsv[2]).abs if d_hue <= threshold and d_saturation <= threshold and d_value <= threshold true else false end end |
#to_hsv ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/cheers/color.rb', line 22 def to_hsv red, green, blue = [r, g, b].collect {|x| x / 255.0} max = [red, green, blue].max min = [red, green, blue].min if min == max hue = 0 elsif max == red hue = 60 * ((green - blue) / (max - min)) elsif max == green hue = 60 * ((blue - red) / (max - min)) + 120 elsif max == blue hue = 60 * ((red - green) / (max - min)) + 240 end saturation = (max == 0) ? 0 : (max - min) / max [hue % 360, saturation, max] end |
#to_s ⇒ Object
16 17 18 19 20 |
# File 'lib/cheers/color.rb', line 16 def to_s return '#' + r.to_s(16).rjust(2, '0') + g.to_s(16).rjust(2, '0') + b.to_s(16).rjust(2, '0') end |