class Camalian::Color

Camalian color object

Attributes

b[R]
g[R]
h[R]
hsv[R]
l[R]
r[R]
s[R]

Public Class Methods

from_hex(hex_value) click to toggle source
# File lib/camalian/color.rb, line 12
def self.from_hex(hex_value)
  color_hash = hex_value[0..6]
  color_hash = color_hash[1..6] if color_hash[0] == '#'
  r = color_hash[0..1].to_i(16)
  g = color_hash[2..3].to_i(16)
  b = color_hash[4..5].to_i(16)

  Color.new(r, g, b)
end
new(r, g, b) click to toggle source
# File lib/camalian/color.rb, line 8
def initialize(r, g, b)
  build_components(r, g, b)
end

Public Instance Methods

==(other) click to toggle source

Used for object comparison

# File lib/camalian/color.rb, line 36
def ==(other)
  r == other.r && g == other.g && b == other.b
end
Also aliased as: eql?
eql?(other)
Alias for: ==
hash() click to toggle source

Used for array uniqueness

# File lib/camalian/color.rb, line 31
def hash
  "#{r}#{g}#{b}".to_i
end
hue_distance(color) click to toggle source
# File lib/camalian/color.rb, line 41
def hue_distance(color)
  [(h - color.h) % 360, (color.h - h) % 360].min
end
rgb_distance(color) click to toggle source
# File lib/camalian/color.rb, line 45
def rgb_distance(color)
  Math.sqrt(((r - color.r)**2) + ((g - color.g)**2) + ((b - color.b)**2))
end
to_hex() click to toggle source
# File lib/camalian/color.rb, line 26
def to_hex
  "##{r.to_s(16).rjust(2, '0')}#{g.to_s(16).rjust(2, '0')}#{b.to_s(16).rjust(2, '0')}"
end
to_s() click to toggle source
# File lib/camalian/color.rb, line 22
def to_s
  "red=#{r} green=#{g} blue=#{b} hue=#{h} saturation=#{s} lightness=#{l}"
end

Private Instance Methods

build_components(r, g, b) click to toggle source
# File lib/camalian/color.rb, line 51
def build_components(r, g, b)
  @r = r
  @g = g
  @b = b

  ri = @r / 255.0
  gi = @g / 255.0
  bi = @b / 255.0

  cmax = [ri, gi, bi].max
  cmin = [ri, gi, bi].min
  delta = cmax - cmin

  @l = (cmax + cmin) / 2.0

  if delta.zero?
    @h = 0
  elsif cmax == ri
    @h = 60 * (((gi - bi) / delta) % 6)
  elsif cmax == gi
    @h = 60 * (((bi - ri) / delta) + 2)
  elsif cmax == bi
    @h = 60 * (((ri - gi) / delta) + 4)
  end

  @s = if delta.zero?
         0
       else
         delta / (1 - (2 * @l - 1).abs)
       end

  @h = @h.round(2)
  @s = (@s * 100).round(2)
  @l = (@l * 100).round(2)

  # HSV Calculation
  # Hue calculation
  if delta.zero?
    @hsv = [0]
  elsif cmax == ri
    @hsv = [60 * (((gi - bi) / delta) % 6)]
  elsif cmax == gi
    @hsv = [60 * (((bi - ri) / delta) + 2)]
  elsif cmax == bi
    @hsv = [60 * (((ri - gi) / delta) + 4)]
  end

  # Saturation calculation
  @hsv << if cmax.zero?
            0
          else
            delta / cmax
          end

  # Value calculation
  @hsv << cmax

  @hsv = [@hsv[0].round(2), (@hsv[1] * 100).round(2), (@hsv[2] * 100).round(2)]
end