问题
I am looking for an algorithm to draw regular polygon like triangle, quadrangle, pentagon, hexagon etc.
I guess it`s basically dealing with the fact that all polygon points are located on the line of the circle.
What`s the algorithm to calculate those N points for Polygon object? After drawing a regular polygon I need to draw another regular polygon based on the first one but rotated by K degrees.
回答1:
Use sin and cos:
double theta = 2 * Math.PI / sides;
for (int i = 0; i < sides; ++i) {
double x = Math.cos(theta * i);
double y = Math.sin(theta * i);
// etc...
}
To rotate just add a constant offset to the angle, i.e. theta * i + offset
.
回答2:
The vertices of an N
-vertex polygon are located at the angles
(2*Math.PI*K)/N
where K
goes from 0 to N-1
, inclusive. The vertical coordinate can be calculated as a sine of the angle times the radius of the circumcircle; the horizontal coordinate is calculated the same way, except you need to multiply the radius by the cosine of the angle.
In order to turn your polygon by X
degrees, convert X
to radians, and add the result to the angle in the formula, like this:
(2*Math.PI*K)/N + Xrad
Finally, since the origin of the screen is in one of the corners, only a portion of your polygon is going to be visible. To avoid this, add an offset equal to the position of the circumcircle's center to each coordinate that you calculate.
回答3:
sin, cos, radius, 2*PI / number of sides and a loop
来源:https://stackoverflow.com/questions/13906352/java-draw-regular-polygon