Class: MagicCloud::Canvas

Inherits:
Object
  • Object
show all
Defined in:
lib/magic_cloud/canvas.rb

Overview

Thin wrapper around RMagick, incapsulating ALL the real drawing. As it’s only class that “knows” about underlying graphics library, it should be possible to replace it with another canvas with same interface, not using RMagick.

Constant Summary collapse

RADIANS =
Math::PI / 180

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(w, h, back = 'transparent') ⇒ Canvas

Returns a new instance of Canvas.



10
11
12
13
# File 'lib/magic_cloud/canvas.rb', line 10

def initialize(w, h, back = 'transparent')
  @width, @height = w, h
  @internal = Magick::Image.new(w, h){|i| i.background_color =  back}
end

Instance Attribute Details

#heightObject (readonly)

Returns the value of attribute height.



15
16
17
# File 'lib/magic_cloud/canvas.rb', line 15

def height
  @height
end

#internalObject (readonly)

Returns the value of attribute internal.



15
16
17
# File 'lib/magic_cloud/canvas.rb', line 15

def internal
  @internal
end

#widthObject (readonly)

Returns the value of attribute width.



15
16
17
# File 'lib/magic_cloud/canvas.rb', line 15

def width
  @width
end

Instance Method Details

#draw_text(text, options = {}) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/magic_cloud/canvas.rb', line 19

def draw_text(text, options = {})
  draw = Magick::Draw.new # FIXME: is it necessary every time?
  
  x = options.fetch(:x, 0)
  y = options.fetch(:y, 0)
  rotate = options.fetch(:rotate, 0)

  set_text_options(draw, options)

  rect = _measure_text(draw, text, rotate)

  draw.
    translate(x + rect.width/2, y + rect.height/2).
    rotate(rotate).
    translate(0, rect.height/8). # RMagick text_align seems really weird
    text(0, 0, text).
    draw(@internal)

  rect
end

#measure_text(text, options) ⇒ Object



40
41
42
43
44
# File 'lib/magic_cloud/canvas.rb', line 40

def measure_text(text, options)
  draw = Magick::Draw.new
  set_text_options(draw, options)
  _measure_text(draw, text, options.fetch(:rotate, 0))
end

#pixels(x, y, w, h) ⇒ Object



46
47
48
# File 'lib/magic_cloud/canvas.rb', line 46

def pixels(x, y, w, h)
  @internal.export_pixels(x, y, w, h, 'RGBA')
end

#renderObject

rubocop:disable TrivialAccessors



51
52
53
# File 'lib/magic_cloud/canvas.rb', line 51

def render
  @internal
end