Drawing star shapes with variable parameters

I have the task of writing a program that allows users to draw stars, which can vary in size and number of weapons. When I was dealing with the main stars, I did this with GeneralPath and point tables:

int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 }; int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 }; Graphics2D g2d = ( Graphics2D ) g; GeneralPath star = new GeneralPath(); star.moveTo( xPoints[ 0 ], yPoints[ 0 ] ); for ( int k = 1; k < xPoints.length; k++ ) star.lineTo( xPoints[ k ], yPoints[ k ] ); star.closePath(); g2d.fill( star ); 

What method to choose for drawing stars with a variable internal and external radius, as well as with different amounts of weapons? This is what I should get:

alt text http://img228.imageshack.us/img228/6427/lab6c.jpg

+6
java swing shapes
source share
3 answers

With n leverage, you end up with 2n vertices, even ones on the outer circle, and odd ones on the inner circle. When viewed from the center, the vertices are located at evenly spaced angles (the angle is 2 * PI / 2 * n = Pi / n). On the unit circle (r = 1), the coordinates x, y of the points i = 0..n are cos (x), sin (x). Multiply these coordinates with the appropriate radius (rOuter or rInner, depending on whether I am odd or even) and add this vector to the center of the star to get the coordinates for each vertex in the star path.

Here is the function of creating a star shape with a given number of hands, a central coordinate and an outer, inner radius:

 public static Shape createStar(int arms, Point center, double rOuter, double rInner) { double angle = Math.PI / arms; GeneralPath path = new GeneralPath(); for (int i = 0; i < 2 * arms; i++) { double r = (i & 1) == 0 ? rOuter : rInner; Point2D.Double p = new Point2D.Double(center.x + Math.cos(i * angle) * r, center.y + Math.sin(i * angle) * r); if (i == 0) path.moveTo(p.getX(), p.getY()); else path.lineTo(p.getX(), p.getY()); } path.closePath(); return path; } 
+19
source share

I think you should use the same classes (GeneralPath), but here you should focus on how to calculate the coordinates of the vertices.

The first thing that comes to my mind is positioning 2N points on a circle of radius R1 centered at (0,0). Then, "strech" each odd vertex, multiplying its vector by c. The constant c must be equal to R2 / R1 (i.e., the fraction of the inner and outer radii).

But maybe there is a simpler solution ...

+3
source share

Here's an example of finding equally spaced points on a circle that might help. Just specify the number of points, n, parameter in the constructor.

 private int n; ... public CircleTest(int n) { ... this.n = n; } ... for (int i = 0; i < n; i++) { double t = 2 * Math.PI * i / n; ... } 
+2
source share

All Articles