-2

I looked up how to draw a star in Java, and I found the following code:

public void paint(Graphics g) {
    drawStar(g,Color.BLACK,5,300,300,100,1…
    drawStar(g,Color.RED,6,100,100,20,20);
    drawStar(g,Color.BLUE,9,200,400,40,40)…
    drawStar(g,Color.YELLOW,27,400,200,10,…
    drawStar(g,Color.GREEN,400,300,300,250…
}

public double circleX(int sides, int angle) {
    double coeff = (double)angle/(double)sides;
    return Math.cos(2*coeff*Math.PI-halfPI);
}

public double circleY(int sides, int angle) {
    double coeff = (double)angle/(double)sides;
    return Math.sin(2*coeff*Math.PI-halfPI);
}

public void drawStar(Graphics g, Color c, int sides, int x, int y, int w, int h) {
    Color colorSave = g.getColor();
    g.setColor(c);
    for(int i = 0; i < sides; i++) {
        int x1 = (int)(circleX(sides,i) * (double)(w)) + x;
        int y1 = (int)(circleY(sides,i) * (double)(h)) + y;
        int x2 = (int)(circleX(sides,(i+2)%sides) * (double)(w)) + x;
        int y2 = (int)(circleY(sides,(i+2)%sides) * (double)(h)) + y;
        g.drawLine(x1,y1,x2,y2);
    }
}
}

halfPI is defined as a private static variable outside the body

I don't quite get the logic behind these methods. Could someone offer an explanation?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user2578330
  • 57
  • 1
  • 2
  • 6
  • 7
    What in particular is the issue? Seems like "playing computer" with a pen and paper would be enough to work through the math. – Dave Newton Sep 01 '13 at 01:15

1 Answers1

1

You can follow the graphics object carefully line by line and see what happens to it. It looks like the writer's algorithm uses sine and cosine the evenly split the circle at the same sized angles depending on the number of sides. Then for each side, it draws the line. It is a good beginner program to test and make it work and don't worry if you can't make the basic math work, those are just rather easy trigonometric expressions depending on the arguments that are passed to the drawing method and the helper methods.

Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424