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.



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

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.



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

def height
  @height
end

#internalObject (readonly)

Returns the value of attribute internal.



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

def internal
  @internal
end

#widthObject (readonly)

Returns the value of attribute width.



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

def width
  @width
end

Instance Method Details

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

rubocop:todo Metrics/AbcSize



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

def draw_text(text, options = {}) # rubocop:todo Metrics/AbcSize
  return nil if text.empty?

  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



43
44
45
46
47
# File 'lib/magic_cloud/canvas.rb', line 43

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



49
50
51
# File 'lib/magic_cloud/canvas.rb', line 49

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

#renderObject



53
54
55
# File 'lib/magic_cloud/canvas.rb', line 53

def render
  @internal
end