Class: Bezier::Painter

Inherits:
Object
  • Object
show all
Defined in:
lib/bezier/painter.rb

Overview

Public: Paint an Array of Points into a PNG file

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ Painter

Public: Contruct a new instance of Bezier::Painter.

Examples

painter = Bezier::Painter.new do |p|
  p.points  = [...]
  p.path    = "Bézier.png"
  p.padding = 20
end

Yields:

  • (_self)

Yield Parameters:



24
25
26
27
28
29
# File 'lib/bezier/painter.rb', line 24

def initialize
  self.points  = []
  self.path    = "Bézier.png"
  self.padding = 10
  yield(self) if block_given?
end

Instance Attribute Details

#paddingObject

Public: The padding to be added to the edges of the image.



13
14
15
# File 'lib/bezier/painter.rb', line 13

def padding
  @padding
end

#pathObject

Public: The path to the output file.



10
11
12
# File 'lib/bezier/painter.rb', line 10

def path
  @path
end

#pointsObject

Public: The Array of Points to be drawn.



7
8
9
# File 'lib/bezier/painter.rb', line 7

def points
  @points
end

Instance Method Details

#get_parametersObject

Internal: Get the parameters associated with this PNG.

Returns a Hash



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/bezier/painter.rb', line 49

def get_parameters
  output = {}

  output[:x_min] = self.points.min_by { |p| p.x }.x
  output[:x_max] = self.points.max_by { |p| p.x }.x
  output[:y_min] = self.points.min_by { |p| p.y  }.y
  output[:y_max] = self.points.max_by { |p| p.y  }.y

  output[:width]  = (output[:x_max] - output[:x_min] + 2 * self.padding).ceil
  output[:height] = (output[:y_max] - output[:y_min] + 2 * self.padding).ceil

  output[:x_offset] = output[:x_min] - self.padding
  output[:y_offset] = output[:y_min] - self.padding

  output
end

#saveObject

Public: Save the PNG

Returns nothing



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/bezier/painter.rb', line 34

def save
  parameters = get_parameters
  image = ChunkyPNG::Image.new(parameters[:width], parameters[:height], ChunkyPNG::Color::WHITE)
  points.each do |pt|
    x = pt.x - parameters[:x_offset]
    y = pt.y - parameters[:y_offset]
    image[x.round, y.round] = ChunkyPNG::Color::BLACK
  end
  p image.class
  image.save(path)
end