Class: Vissen::Output::Color

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

Overview

Basic value object representing a color in the RGB color space.

Usage

The following example creates two colors, mixes them, and converts the result to an array of color component.

color_a = Color.new 0.3, 0.6, 0.2
color_b = Color.new 0.1, 0.2, 0.5

color_a.mix_with(color_b, 0.5).to_a => [0.2, 0.3, 0.35]

Direct Known Subclasses

Pixel

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(r = 0.0, g = 0.0, b = 0.0) ⇒ Color



23
24
25
26
27
# File 'lib/vissen/output/color.rb', line 23

def initialize(r = 0.0, g = 0.0, b = 0.0)
  @r = r
  @g = g
  @b = b
end

Instance Attribute Details

#bObject

Accessors for the red, green and blue color components.



18
19
20
# File 'lib/vissen/output/color.rb', line 18

def b
  @b
end

#gObject

Accessors for the red, green and blue color components.



18
19
20
# File 'lib/vissen/output/color.rb', line 18

def g
  @g
end

#rObject

Accessors for the red, green and blue color components.



18
19
20
# File 'lib/vissen/output/color.rb', line 18

def r
  @r
end

Class Method Details

.from(obj) ⇒ Color

Cast a given object to a color.



94
95
96
97
98
99
100
101
102
# File 'lib/vissen/output/color.rb', line 94

def from(obj)
  case obj
  when self    then obj
  when Array   then new(*obj)
  when Integer then from_integer obj
  else
    new(*obj.to_a)
  end
end

Instance Method Details

#==(other) ⇒ true, false

Color equality based on component values.

TODO: Add some small delta around what is considered the same color?

Perhaps scale to 255 and floor before comparing?


36
37
38
39
40
# File 'lib/vissen/output/color.rb', line 36

def ==(other)
  r == other.r && g == other.g && b == other.b
rescue NoMethodError
  false
end

#inspectString

Returns a string formatted in the tradiotioal hex representation of a color: #04A4BF.



84
85
86
# File 'lib/vissen/output/color.rb', line 84

def inspect
  format('#%02X%02X%02X', *to_a.map! { |v| (v * 255).round })
end

#mix_with(other, ratio) ⇒ Color

Returns a new color that is a mix between this and the other color, based on the ratio. See ‘#mix_with!` for more details.



76
77
78
# File 'lib/vissen/output/color.rb', line 76

def mix_with(other, ratio)
  dup.mix_with! other, ratio
end

#mix_with!(other, ratio) ⇒ self

Moves this color toword the other based on the given ratio.

ratio = 0 -> 100 % of this color ratio = 1 -> 100 % of the other color



60
61
62
63
64
65
66
67
68
# File 'lib/vissen/output/color.rb', line 60

def mix_with!(other, ratio)
  anti_ratio = (1 - ratio)

  self.r = r * anti_ratio + other.r * ratio
  self.g = g * anti_ratio + other.g * ratio
  self.b = b * anti_ratio + other.b * ratio

  self
end

#to_aArray<Float>

Creates a new array from the color.



46
47
48
# File 'lib/vissen/output/color.rb', line 46

def to_a
  [r, g, b]
end