Class: Yeah::Color

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

Overview

A Color represents a color with an alpha value.

Examples:

Comparing two colors

Color.new(100, 100, 100) == Color.new('#646464')
# => true

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(red, green, blue, alpha) ⇒ Color #initialize(hex_string, alpha) ⇒ Color

Returns a new instance of Color

Overloads:

  • #initialize(red, green, blue, alpha) ⇒ Color

    Parameters:

    • red (Integer)

      value, from 0 to 255

    • green (Integer)

      value, from 0 to 255

    • blue (Integer)

      value, from 0 to 255

    • alpha (Float)

      value, from 0.0 to 1.0, defaults to 1.0

  • #initialize(hex_string, alpha) ⇒ Color

    Parameters:

    • color (String)

      value in hexadecimal '#dadada' or '#fff' format

    • alpha (Float)

      value, from 0.0 to 1.0, defaults to 1.0


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/yeah/color.rb', line 20

def initialize(*args)
  if args[0].respond_to?(:[]) && args[0][0] == '#' # hex string
    if args[0].length == 4 # short hex
      @value = args[0][1..3].chars.map { |h| "#{h}#{h}".to_i(16) }
    else # normal hex
      @value = args[0][1..6].scan(/../).map { |h| h.to_i(16) }
    end

    @value[3] = args[1] || 1.0
  else
    @value = args
    @value[3] ||= 1.0
  end

  @hex = "##{@value[0..2].map { |v| v.to_s(16).rjust(2, '0') }.join }"
end

Instance Attribute Details

#valueArray (readonly)

Returns color value in RGBA format

Returns:

  • (Array)

    color value in RGBA format


10
11
12
# File 'lib/yeah/color.rb', line 10

def value
  @value
end

Instance Method Details

#==(other) ⇒ true, false

Returns whether self matches other color

Returns:

  • (true, false)

    whether self matches other color


43
44
45
# File 'lib/yeah/color.rb', line 43

def ==(other)
  value == other.value
end

#inspectString

Returns readable representation

Returns:

  • (String)

    readable representation


38
39
40
# File 'lib/yeah/color.rb', line 38

def inspect
  "#{self.class.name}#{value.to_s}"
end

#to_hexString

Returns color value as an RGB hex string

Returns:

  • (String)

    color value as an RGB hex string


48
49
50
# File 'lib/yeah/color.rb', line 48

def to_hex
  @hex
end