Module: GridToPic

Included in:
SquareGrid
Defined in:
lib/hex/modules/grid_to_pic.rb

Overview

This module contain the methods to draw a grid to a picture file.

Instance Method Summary collapse

Instance Method Details

#to_pic(pic_name, exit_on_error = true) ⇒ Boolean

Draw the hex grid on a Magick::Object and save it to a file

Parameters:

  • exit_on_error (Boolean) (defaults to: true)

    by default, if you call this method and rmagic is not installed, the program exit with an error. You can disable it and make the program continue

  • pic_name (String)

    the name of the picture file (can be *.bmp, *.png, *.jpg)

Returns:

  • (Boolean)

    true if the file was created successfully, false otherwise



52
53
54
55
# File 'lib/hex/modules/grid_to_pic.rb', line 52

def to_pic( pic_name, exit_on_error = true )
  canvas = to_rmagick_image( exit_on_error )
  canvas.write( pic_name )
end

#to_rmagick_image(exit_on_error = true) ⇒ Magick::Image

Draw the hex grid in a Magick::Image object

Parameters:

  • exit_on_error (Boolean) (defaults to: true)

    by default, if you call this method and rmagic is not installed, the program exit with an error. You can disable it and make the program continue.

Returns:

  • (Magick::Image)

    a Magick::Image object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/hex/modules/grid_to_pic.rb', line 19

def to_rmagick_image( exit_on_error = true )
  unless defined?( Magick::Image ) && defined?( Magick::HatchFill ) && defined?( Magick::Draw )
    puts 'Rmagick is not installed !!! You can\'t dump hex grid to pic'
    exit if exit_on_error
  end

  maxx = ( @hexes.keys.map{ |k| k[0] + k[1]/2 }.max ) * @hex_width + ( @hex_width + @half_width + 1 )
  maxy = @hexes.keys.map{ |k| k[1] }.max * ( ( @hex_height * 3.0 )/ 4.0 ).ceil + ( @hex_height + 1 )

  # maxx = ( ( @hexes.keys.map{ |k| k[0] + k[1]/2 }.max ) + 0.5 ) * @hex_width
  # maxy = ( ( @hexes.keys.map{ |k| k[1] }.max * 3.0/4.0 ) + 0.5 ) + @hex_heig

  canvas = Magick::Image.new( maxx, maxy )

  gc = Magick::Draw.new
  gc.stroke_antialias( true )
  gc.stroke( 'black' )
  gc.stroke_opacity( '60%' )

  @hexes.each{ | _, hex| draw_hex( gc, hex ) }

  gc.draw(canvas)

  canvas
end

#to_xy(hex) ⇒ Array<Integer>

Get the (x, y) position of an hexagon object

Parameters:

  • hex (AxialHex)

    the hexagon you want to get the position

Returns:

  • (Array<Integer>)

    an array of two integers corrsponding respectively to the x, y values



63
64
65
66
67
68
69
70
71
# File 'lib/hex/modules/grid_to_pic.rb', line 63

def to_xy( hex )
  x = ( @hex_ray * Math.sqrt(3) * ( hex.q + hex.r/2.0 ) )
  y = ( @hex_ray * 3.0/2.0 * hex.r )

  x += @half_width
  y += @half_height

  [ x, y ]
end