Class: PaletteTown::Color

Inherits:
Object
  • Object
show all
Defined in:
lib/palettetown/color.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(color) ⇒ Color

Returns a new instance of Color.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/palettetown/color.rb', line 4

def initialize color
  if color.is_a? String
    color = self.class.from_hex(color)
  elsif color.is_a? Fixnum
    color = self.class.from_hex("%06x" % color)
  elsif color.is_a? PaletteTown::Color
    color = color.to_h
  elsif color.is_a? Hash
    if color[:hue].nil? or color[:sat].nil? or color[:lum].nil?
      raise ArgumentError
    end
  end
  @hue = color[:hue].to_f
  @sat = color[:sat].to_f
  @lum = color[:lum].to_f
end

Instance Attribute Details

#hueObject

Returns the value of attribute hue.



3
4
5
# File 'lib/palettetown/color.rb', line 3

def hue
  @hue
end

#lumObject

Returns the value of attribute lum.



3
4
5
# File 'lib/palettetown/color.rb', line 3

def lum
  @lum
end

#satObject

Returns the value of attribute sat.



3
4
5
# File 'lib/palettetown/color.rb', line 3

def sat
  @sat
end

Instance Method Details

#to_hObject



44
45
46
47
48
49
50
# File 'lib/palettetown/color.rb', line 44

def to_h
  return {
    :hue => @hue,
    :sat => @sat,
    :lum => @lum
  }
end

#to_hexObject



41
42
43
# File 'lib/palettetown/color.rb', line 41

def to_hex
  "%<r>02x%<g>02x%<b>02x" % to_rgb
end

#to_rgbObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/palettetown/color.rb', line 20

def to_rgb
  if @sat == 0
    r = g = b = @lum
  else
    y = if @lum < 0.5
      @lum * (@sat + 1.0)
    else
      @lum + @sat - (@lum * @sat)
    end
    x = @lum * 2.0 - y
    # Why are we using 2pi here?  Because we're using Radians, bitch.
    r = self.class.hue_to_rgb(x, y, @hue * Math::PI * 2 + 1.0/3.0)
    g = self.class.hue_to_rgb(x, y, @hue * Math::PI * 2)
    b = self.class.hue_to_rgb(x, y, @hue * Math::PI * 2 - 1.0/3.0)
  end
  return {
    :r => (r * 255).to_i,
    :g => (g * 255).to_i,
    :b => (b * 255).to_i
  }
end

#to_sObject



51
52
53
# File 'lib/palettetown/color.rb', line 51

def to_s
  "##{to_hex}"
end