ブレゼンハムのアルゴリズム(Ruby)

ja.wikipedia.org「ブレゼンハムのアルゴリズム」とは画面に線分を描くアルゴリズムです。コードはここJava 版を移植させていただきました。

Ruby コードです。描画に Cairo を使っています。

require "cairo"

class Draw
  W = 400
  Side = 10
  
  def initialize  
    @surface = Cairo::ImageSurface.new(W, W)
    @context = Cairo::Context.new(@surface)
    
    #背景色
    @context.set_source_color(Cairo::Color::BLACK)
    @context.rectangle(0, 0, W, W)
    @context.fill
  end
  
  def point(x, y)
    @context.set_source_color(Cairo::Color.parse("#73F829"))
    x1 = x * Side
    y1 = y * Side
    @context.rectangle(x1, y1, Side, Side)
    @context.fill
  end
  
  def finish
    @surface.write_to_png("pic.png")
  end
  
  def self.exe(&bk)
    d = Draw.new
    d.instance_exec(&bk)
    d.finish
  end
end


def bresenham(x0, y0, x1, y1)
  dx = x1 - x0
  step_x = (dx >= 0) ? 1 : -1
  dy = y1 - y0
  step_y = (dy >= 0) ? 1 : -1
  
  dx = dx.abs * 2
  dy = dy.abs * 2
  
  @f.point(x0, y0)
  x = x0
  y = y0
  
  if dx > dy
    fraction = dy - dx / 2
    until x == x1
      if fraction >= 0
        y += step_y
        fraction -= dx
      end
      x += step_x
      fraction += dy
      @f.point(x, y)
    end
  else
    fraction = dx - dy / 2
    until y == y1
      if fraction >= 0
        x += step_x
        fraction -= dy
      end
      y += step_y
      fraction += dx
      @f.point(x, y)
    end
  end
end


if $0 == __FILE__
  @f = Draw.new
  bresenham( 3,  3, 35, 15)
  bresenham(35, 15, 18, 37)
  bresenham(18, 37,  3,  3)
  @f.finish
end

メソッドbresenham が求めるものです。Drawクラスは Cairo での描画をしています。

結果はこんな感じです。
20200123012619