Problém ako umiestniť body po na kružnici som riešil nedávno a vôbec to nie je zložité.
Potrebujeme k tomu 3 údaje a to počet bodov, šírku a výšku plátna na ktoré ideme body umiestňovať.
Prvú vec ktorú si spočítame sú okraje kružnice. V mojom uvedenom príklade je to veľkosť plátna mínus 10%. Ďalej si určíme uhol alfa ktorý vypočítame ako 2 × π a to celé deleno počet vrcholov.
Ako ďalšiu vec si určíme stred kružnice a polomer. A na koniec už len prechádzame počtom vrcholov a jednoduchou matematickou operáciou pre x-ovú súradnicu je to stred + (polomer × cos(poradie vrchola × uhol alfa)) a pre y-ovú je postup rovnaký avšak zmeníme funkciu cos() na funkciu sin() počítame už konkrétne body.
Realizácia v Jave
/**
* placePointsOnCircle - Regular distribution of points on a circle
*
* @author Tomas Adamjak <thomas @ adamjak.net>
*
* @see http://thomas.adamjak.net/2014/03/27/ako-umiestnit-body-na-kruznicu/
*
* @param numberOfPoint (Integer) - Number of points that we want to place the circle (must be at least 1)
* @param width (Integer) - canvas width
* @param height (Integer) - canvas height
*
* @return List<Point> - List of points
*
* @throws Exception If number of points is less than 1
* @throws Exception If width of canvas is less than 1
* @throws Exception If height of canvas is less than 1
*/
public List<Point> placePointsOnCircle(Integer numberOfPoint, Integer width, Integer height) throws Exception
{
if (width < 0)
{
throw new Exception("Width must be more than 0.");
}
else if (height < 0)
{
throw new Exception("Height must be more than 0.");
}
else if (numberOfPoint < 0)
{
throw new Exception("Number of points must be more than 0.");
}
Integer minWidth = width / 100 * 10;
Integer maxWidth = width - minWidth;
Integer minHeight = height / 100 * 10;
Integer maxHeight = height - minHeight;
Double angleAlfa = (2 * Math.PI) / numberOfPoint;
Point center = new Point((maxWidth + minWidth) / 2, (maxHeight + minHeight) / 2);
Integer radius = null;
if ((maxWidth - center.x) > (maxHeight - center.y))
{
radius = maxHeight - center.y;
}
else
{
radius = maxWidth - center.x;
}
List<Point> points = new ArrayList<Point>();
for (int i = 0; i < numberOfPoint; i++)
{
Double x = center.x + (radius * Math.cos(i * angleAlfa));
Double y = center.y + (radius * Math.sin(i * angleAlfa));
points.add(new Point(x.intValue(), y.intValue()));
}
return points;
}
Komentáre
Zverejnenie komentára