Mae向きなブログ

Mae向きな情報発信を続けていきたいと思います。

コッホ曲線

cairo:2次元画像描画ライブラリを読んでみました。丁寧な説明がなされているので非常に分かりやすかったです。

読んだだけでは面白くないので、なんか題材はないかと考えたのですが、あんまりデザインのセンスがないので良い題材が思い浮かびません…。
とりあえず、H18年春季基本情報技術者試験午後問題の問6で出題されたコッホ曲線を作ってみました。
koch_curve.rb

require 'cairo'
include Math

def DrawLine(x1, y1, x2, y2)
  $context.set_source_rgb(1, 0, 0)
  $context.move_to(x1, y1)
  $context.line_to(x2, y2)
  $context.stroke
end

def KochCurve(x1, y1, x2, y2, dim)
  if dim <= 0
    DrawLine(x1, y1, x2, y2) 
  else
    x3 = (2 * x1 + x2) / 3
    y3 = (2 * y1 + y2) / 3
    x5 = (x1 + 2 * x2) / 3
    y5 = (y1 + 2 * y2) / 3
    x4 = x3 + (x5 - x3) * cos(PI/3) +
      (y5 - y3) * sin(PI/3)
    y4 = y3 - (x5 - x3) * sin(PI/3) +
      (y5 - y3) * cos(PI/3)
    KochCurve(x1, y1, x3, y3, dim - 1)
    KochCurve(x3, y3, x4, y4, dim - 1)
    KochCurve(x4, y4, x5, y5, dim - 1)
    KochCurve(x5, y5, x2, y2, dim - 1)
  end
end

format = Cairo::FORMAT_ARGB32
width = 300
height = 300

$surface = Cairo::ImageSurface.new(format, width, height)
$context = Cairo::Context.new($surface)

$context.set_source_rgb(1, 1, 1)
$context.rectangle(0, 0, width, height)
$context.fill
$context.translate(40, 40)

KochCurve(  0,   0,   0, 180, 2)
KochCurve(  0, 180, 180, 180, 2)
KochCurve(180, 180, 180,   0, 2)
KochCurve(180,   0,   0,   0, 2)

$surface.write_to_png("koch_curve.png")

ところで、コマンドラインから画像を見る場合、皆さんどんなコマンドを使っているのでしょう?大昔、学生時代は、xvを使っていたのですが、command not foundでした。やっと、eogというのを見つけました。環境は、Debian GNU/Linux 4.0です。

mmasa@debian:~/work/ruby/cairo$ ruby koch_curve.rb; eog koch_curve.png  &

f:id:rahaema:20200419083436p:plain

Javaでタートルグラフィックス

以前Javaで同じようなことをやった気がします…。