benovermyer / voronoi
使用Fortune算法生成Voronoi多边形
0.1.0
2020-09-24 17:27 UTC
Requires
- php: >=7.4.0
Requires (Dev)
- phpunit/phpunit: ^9.3
This package is auto-updated.
Last update: 2024-09-25 02:41:38 UTC
README
这允许您通过根据一组点计算多边形坐标来自动创建Voronoi图。
它最初由Samuel Roze编写,基于Raymond Hill的JavaScript库。
示例用法
要生成多边形,您需要一个定义您将在其中计算图的盒子的 边界框。然后,您需要一些点。以下是一个简单的代码段,生成随机点并计算多边形。
要获取更完整的示例,请查看文件 sample/voronoi.php
。
注意,边界框在变量 $bbox
中,点在 $sites
中。
<?php use Voronoi\Voronoi; use Voronoi\Point; // Create the bounding box $bbox = new stdClass(); $bbox->xl = 0; $bbox->xr = 400; $bbox->yt = 0; $bbox->yb = 400; // Define generated points bounds $xo = 0; $dx = $width = 400; $yo = 0; $dy = $height = 400; $n = 20; // Generate random points $sites = []; for ($i=0; $i < $n; $i++) { $point = new Point(rand($xo, $dx), rand($yo, $dy)); $sites[] = $point; } // Compute the diagram $voronoi = new Voronoi(); $diagram = $voronoi->compute($sites, $bbox);
现在,您在变量 $diagram['cells']
中有了单元格(多边形)。有了这个,您可以绘制一个代表点和多边形的图像
// Create image using GD $im = imagecreatetruecolor(400, 400); // Create colors $white = imagecolorallocate($im, 255, 255, 255); $red = imagecolorallocate($im, 255, 0, 0); $green = imagecolorallocate($im, 0, 100, 0); $black = imagecolorallocate($im, 0, 0, 0); // Fill white background imagefill($im, 0, 0, $white); // Draw points for ($i=0; $i < $n; $i++) { $point = $sites[$i]; imagerectangle($im, $point->x - 2, $point->y - 2, $point->x + 2, $point->y + 2, $black); } // Draw polygons $j = 0; foreach ($diagram['cells'] as $cell) { $points = array(); if (count($cell->half_edges) > 0) { $v = $cell->half_edges[0]->getStartPoint(); if ($v) { $points[] = $v->x; $points[] = $v->y; } else { var_dump($j.': no start point'); } for ($i = 0; $i < count($cell->half_edges); $i++) { $halfedge = $cell->half_edges[$i]; $edge = $halfedge->edge; if ($edge->va && $edge->vb) { imageline($im, $edge->va->x, $edge->va->y, $edge->vb->x, $edge->vb->y, $red); } $v = $halfedge->getEndPoint(); if ($v) { $points[] = $v->x; $points[] = $v->y; } } } // Create polygon with a random color $color = imagecolorallocatealpha($im, rand(0, 255), rand(0, 255), rand(0, 255), 50); imagefilledpolygon($im, $points, count($points) / 2, $color); $j++; } // Display image imagepng($im, 'voronoi.png');