werd
werd

Reputation: 646

JAVA draw regular polygon

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.

Upvotes: 1

Views: 10977

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

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.

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838066

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.

Upvotes: 5

Tom
Tom

Reputation: 1221

sin, cos, radius, 2*PI / number of sides and a loop

Upvotes: 0

Related Questions