LoginSignup
3

More than 5 years have passed since last update.

「プログラムでシダを描画する」を JRubyFX(Canvas) + FXML で描画する

Posted at

jrubyfxの学習をするために今更感があるシダを描画してみた。

jrubyfxの学習がメインなのでRubyコードはほぼ先人のコードをまるっと頂きました。
でもかなり勉強になりました。

shidaじゃなくてsidaなのは趣味です。

sida.rb
# coding: utf-8

require 'jrubyfx'

fxml_root File.dirname(__FILE__) + '/ui'
class SidaController
  include JRubyFX::Controller
  N = 20
  DEFAULT_WIDTH   = 500
  DEFAULT_HEIGHT  = 500
  W1x = -> (x, y) { 0.836 * x + 0.044 * y }
  W1y = -> (x, y) { -0.044 * x + 0.836 * y + 0.169 }
  W2x = -> (x, y) { -0.141 * x + 0.302 * y }
  W2y = -> (x, y) { 0.302 * x + 0.141 * y + 0.127 }
  W3x = -> (x, y) { 0.141 * x - 0.302 * y }
  W3y = -> (x, y) { 0.302 * x + 0.141 * y + 0.169 }
  W4x = -> (x, y) { 0 }
  W4y = -> (x, y) { 0.175337 * y }
  fxml "sida.fxml"
  def initialize
    gc = @sida_canvas.getGraphicsContext2D
    gc.set_stroke(Color::GREEN)
    gc.set_fill(Color::BLACK)
    gc.set_line_width(1)
    gc.fill_rect(0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT)

    f = -> (k, x, y) do
      if 0 < k
        f.(k - 1, W1x.(x, y), W1y.(x, y))
        f.(k - 1, W2x.(x, y), W2y.(x, y)) if Random.rand < 0.3
        f.(k - 1, W3x.(x, y), W3y.(x, y)) if Random.rand < 0.3
        f.(k - 1, W4x.(x, y), W4y.(x, y)) if Random.rand < 0.3
      else
        xx = (x * 490 + DEFAULT_WIDTH * 0.5).to_i
        yy = (DEFAULT_HEIGHT - y * 490).to_i
        gc.stroke_line(xx, yy, xx, yy)
      end
    end
    -> (k, x, y) {f.(k, x, y) }.(N, 0, 0)
  end
end
class Sida < JRubyFX::Application
  def start(stage)
    with(stage, title: "Sida by jrubyfx") do
      SidaController.load_into stage
      stage.show
    end
  end
end
Sida.launch

fxmlはscene builderで作った。

ui/sida.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.Group?>
<?import javafx.scene.canvas.Canvas?>

<Group xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <Canvas fx:id="sida_canvas" height="500.0" width="500.0" />
   </children>
</Group>

sida.png

課題的ななにか

  • プログラムで何かを描画するということがあまりわかっていない
  • stroke_lineでドットを打つってどうなのよ
  • Rubyぽい書き方とJavaぽい書き方が同居してて気持ち悪い。
  • warbleでjarファイルにして実行したら.jrubyfx_cacheなるディレクトリでぱーみっしょんでないどする。
  • つか.jrubyfx_cacheって何!

jrubyfx + FXML情報少なすぎ。
とりあえずjrubyfxの学習という意味では成果あり。
それっぽいものが描けた。

元ネタとか参考とか

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3