Class: Colors::RGBA

Inherits:
RGB show all
Includes:
AlphaComponent
Defined in:
lib/colors/rgba.rb

Instance Attribute Summary

Attributes included from AlphaComponent

#a

Attributes inherited from RGB

#b, #g, #r

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from RGB

#hsl_components, #to_hex_string, #to_husl, #to_xterm256, #to_xyz

Methods inherited from AbstractColor

#inspect

Constructor Details

#initialize(r, g, b, a) ⇒ RGBA

Returns a new instance of RGBA.



30
31
32
# File 'lib/colors/rgba.rb', line 30

def initialize(r, g, b, a)
  @r, @g, @b, @a = canonicalize(r, g, b, a)
end

Class Method Details

.parse(hex_string) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/colors/rgba.rb', line 3

def self.parse(hex_string)
  error_message = "must be a hexadecimal string of " +
                  "`#rrggbbaa`, `#rgba`, `#rrggbb` or `#rgb` form"
  unless hex_string.respond_to?(:to_str)
    raise ArgumentError, "#{error_message}: #{hex_string.inspect}"
  end

  hex_string = hex_string.to_str
  hexes = hex_string.match(/\A#(\h+)\z/) { $1 }
  case hexes&.length
  when 3  # rgb
    r, g, b = hexes.scan(/\h/).map {|h| h.hex * 17 }
    new(r, g, b, 255)
  when 6  # rrggbb
    r, g, b = hexes.scan(/\h{2}/).map(&:hex)
    new(r, g, b, 255)
  when 4 # rgba
    r, g, b, a = hexes.scan(/\h/).map {|h| h.hex * 17 }
    new(r, g, b, a)
  when 8 # rrggbbaa
    r, g, b, a = hexes.scan(/\h{2}/).map(&:hex)
    new(r, g, b, a)
  else
    raise ArgumentError, "#{error_message}: #{hex_string.inspect}"
  end
end

Instance Method Details

#==(other) ⇒ Object



40
41
42
43
44
45
46
47
48
49
# File 'lib/colors/rgba.rb', line 40

def ==(other)
  case other
  when RGBA
    r == other.r && g == other.g && b == other.b && a == other.a
  when RGB
    r == other.r && g == other.g && b == other.b && a == 1r
  else
    super
  end
end

#componentsObject



36
37
38
# File 'lib/colors/rgba.rb', line 36

def components
  [r, g, b, a]
end

#desaturate(factor) ⇒ Object



51
52
53
# File 'lib/colors/rgba.rb', line 51

def desaturate(factor)
  to_hsla.desaturate(factor).to_rgba
end

#to_hslObject



68
69
70
71
72
73
74
75
# File 'lib/colors/rgba.rb', line 68

def to_hsl
  if a == 1r
    super
  else
    raise NotImplementedError,
          "Unable to convert non-opaque RGBA to RGB"
  end
end

#to_hslaObject



77
78
79
# File 'lib/colors/rgba.rb', line 77

def to_hsla
  HSLA.new(*hsl_components, a)
end

#to_rgbObject



55
56
57
58
59
60
61
62
# File 'lib/colors/rgba.rb', line 55

def to_rgb
  if a == 1r
    RGB.new(r, g, b)
  else
    raise NotImplementedError,
          "Unable to convert non-opaque RGBA to RGB"
  end
end

#to_rgbaObject



64
65
66
# File 'lib/colors/rgba.rb', line 64

def to_rgba
  self
end