Class: HotCocoa::Graphics::Gradient

Inherits:
Object
  • Object
show all
Defined in:
lib/hotcocoa/graphics/gradient.rb

Overview

draw a smooth gradient between any number of key colors

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*colors) ⇒ Gradient

create a new gradient from black to white



24
25
26
27
28
29
30
31
# File 'lib/hotcocoa/graphics/gradient.rb', line 24

def initialize(*colors)
  @colorspace = CGColorSpaceCreateWithName(KCGColorSpaceGenericRGB)
  colors = colors[0] if colors[0].class == Array
  set(colors)
  pre(true)
  post(true)
  self
end

Instance Attribute Details

#drawpostObject (readonly)

Returns the value of attribute drawpost.



21
22
23
# File 'lib/hotcocoa/graphics/gradient.rb', line 21

def drawpost
  @drawpost
end

#drawpreObject (readonly)

Returns the value of attribute drawpre.



21
22
23
# File 'lib/hotcocoa/graphics/gradient.rb', line 21

def drawpre
  @drawpre
end

#gradientObject (readonly)

Returns the value of attribute gradient.



21
22
23
# File 'lib/hotcocoa/graphics/gradient.rb', line 21

def gradient
  @gradient
end

Instance Method Details

#post(tf = nil) ⇒ Object

extend gradient after end location? (true/false)



57
58
59
60
# File 'lib/hotcocoa/graphics/gradient.rb', line 57

def post(tf=nil)
  @drawpost = (tf ? KCGGradientDrawsAfterEndLocation : 0) unless tf.nil?
  @drawpost
end

#pre(tf = nil) ⇒ Object

extend gradient before start location? (true/false)



51
52
53
54
# File 'lib/hotcocoa/graphics/gradient.rb', line 51

def pre(tf=nil)
  @drawpre = (tf ? KCGGradientDrawsBeforeStartLocation : 0) unless tf.nil?
  @drawpre
end

#set(colors) ⇒ Object

create a gradient that evenly distributes the given colors



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/hotcocoa/graphics/gradient.rb', line 34

def set(colors)
  colors ||= [Color.black, Color.white]
  cgcolors = []
  locations = []
  increment = 1.0 / (colors.size - 1).to_f
  i = 0
  colors.each do |c|
    cgcolor = CGColorCreate(@colorspace, [c.r, c.g, c.b, c.a])
    cgcolors.push(cgcolor)
    location = i * increment
    locations.push(location)
    i = i + 1
  end
  @gradient = CGGradientCreateWithColors(@colorspace, cgcolors, locations)
end