Voronoi diagram: Difference between revisions
Content added Content deleted
Line 2,474: | Line 2,474: | ||
Uses [[Raster graphics operations/Ruby]] |
Uses [[Raster graphics operations/Ruby]] |
||
[[File:voronoi_rb.png|thumb|right|Sample output from Ruby program]] |
[[File:voronoi_rb.png|thumb|right|Sample output from Ruby program]] |
||
<lang ruby> |
<lang ruby># frozen_string_literal: true |
||
require_relative 'raster_graphics' |
|||
class ColourPixel < Pixel |
class ColourPixel < Pixel |
||
Line 2,484: | Line 2,486: | ||
def distance_to(px, py) |
def distance_to(px, py) |
||
Math |
Math.hypot(px - x, py - y) |
||
end |
end |
||
end |
end |
||
width |
width = 300 |
||
height = 200 |
|||
npoints = 20 |
npoints = 20 |
||
pixmap = Pixmap.new(width,height) |
pixmap = Pixmap.new(width, height) |
||
@bases = npoints.times.collect do | |
@bases = npoints.times.collect do |_i| |
||
ColourPixel.new( |
ColourPixel.new( |
||
3 + rand(width - 6), 3 + rand(height - 6), # provide a margin to draw a circle |
|||
RGBColour.new(rand(256), rand(256), rand(256)) |
|||
) |
) |
||
end |
end |
||
pixmap.each_pixel do |x, y| |
pixmap.each_pixel do |x, y| |
||
nearest = @bases.min_by {|base| base.distance_to(x, y)} |
nearest = @bases.min_by { |base| base.distance_to(x, y) } |
||
pixmap[x, y] = nearest.colour |
pixmap[x, y] = nearest.colour |
||
end |
end |
||
@bases.each do |base| |
@bases.each do |base| |
||
pixmap[base.x, base.y] = RGBColour::BLACK |
pixmap[base.x, base.y] = RGBColour::BLACK |
||
pixmap.draw_circle(base, 2, RGBColour::BLACK) |
pixmap.draw_circle(base, 2, RGBColour::BLACK) |
||
end |
end |
||
pixmap.save_as_png( |
pixmap.save_as_png('voronoi_rb.png')</lang> |
||
{{libheader|RubyGems}} |
{{libheader|RubyGems}} |