RMagickで手書き風の円

December 16, 2019

https://ruby.tnantoka.com/entry/2019/12/16/211505

Rubyでやるなら使い慣れたRMagickでいくのがいいのか?という気がしてきた。

ということで、以下で描いた手書きの円をRMagickでやってみます。

https://ruby.tnantoka.com/entry/2019/12/13/224549

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# frozen_string_literal: true

require 'bundler/setup'
Bundler.require
include Magick # rubocop:disable Style/MixinUsage

tmp = File.expand_path('../tmp', __dir__)
path = "#{tmp}/image.png"

image = Image.new(300, 300) { self.background_color = 'black' }

Point = Struct.new(:x, :y)

center = Point.new(150, 150)
radius = 100
n1d = Perlin::Noise.new 1

points = 0.upto(360).map do |degrees|
  radians = degrees * Math::PI / 180
  noise = 1 + n1d[radians] * 0.3
  Point.new(
    center.x + Math.cos(radians) * radius * noise,
    center.y + Math.sin(radians) * radius * noise
  )
end

draw = Draw.new
draw.stroke('white').stroke_width(1)

draw.polygon(*points.flat_map { |p| [p.x, p.y] })

draw.draw(image)

image.write(path)
`open #{path}`

https://github.com/tnantoka/ruby.tnantoka.com/blob/a7df8ae37bac373b5257665f447c7a589f1faa98/rmagick/circle.rb

短い…!

出力された画像がこちら。手書き風の円になっています。

かなり楽だったので、少なくとも静止画は慣れたRMagickでいこうと思います。