Hi guys.

Need some mathematics assistance. Imagine you are given a circle that acts as a bounding box. How do you accurately draw a polygon in such a way that it fits the circle just nice? Note that I meant a polygon, meaning that the algorithm must be able to cater for any number of sides 3 or above. I will really appreciate it if any one of you can post the code to accomplish this. You can start your code with:

public void paintComponent(Graphics g)

{

super.paintComponent(g);

// For sake of clarity, assume that the radius of the bounding box (circle) is 100 pixels

// Now draw a polygon to fit this circle

}

I have an idea of what to do, but I cannot code it because I have forgotten all my trigonometry. The idea is this:

In order to draw a polygon that fits in a circle perfectly, the theory is that all the points must touch the circle. In order to make this happen, I take 360 degrees and divide by the number of points (which happens to be equal to the number of sides). Once I know the answer, the problem becomes simpler. All I need to do is start from the center of the circle, draw an imaginary line outwards until it touches the circle (and if you notice, this line happens to be the radius). Everytime after I draw a line this way, I will rotate the same angle as the angle I just found out, then I draw an imaginary line the same way, and keep continuing until I finish drawing all the lines. Once all imaginary lines are drawn, just connect all the points (a point is defined as the location where the imaginary line and circle intersect) together to form a polygon. Although I know the theory, but, I do not know how to find out the x and y coordinates of the point where the imaginary line touches the circle.

Can anyone please help? Thanks a lot. Also, if your theory of drawing a polygon in a circle is simpler than mine, feel free to use your own.

import java.awt.*;

public class CirclePolygon extends JPanel

{

private Polygon Poly = createPolygon(8, 105, 105, 100);

public static void main(String[] args)

{

JFrame f = new JFrame();

f.getContentPane().add(new

f.setSize(220, 240);

f.show();

}

public void paintComponent(Graphics g)

{

g.drawPolygon(Poly);

}

public static Polygon createPolygon(int n, int cx, int cy, int r)

{

double delta = 2 * Math.PI / n;

Polygon p = new Polygon();

double theta = 0.0;

for (int i=0; i<n; i++)

{

int x = cx + (int) (r * Math.cos(theta));

int y = cy + (int) (r * Math.sin(theta));

theta += delta;

p.addPoint(x, y);

}

return p;

}

}