Saturday 31 August 2013

Code to draw a star

Code to draw a star

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?

No comments:

Post a Comment