代码画一颗星

时间:2013-09-01 01:12:04

标签: java awt paint java-2d

我查看了如何在Java中绘制一个星,我找到了以下代码:

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被定义为正文之外的私有静态变量

我不太了解这些方法背后的逻辑。有人可以提供解释吗?

1 个答案:

答案 0 :(得分:1)

您可以逐行仔细跟踪图形对象,看看它会发生什么。看起来作者的算法使用正弦和余弦,根据边的数量,以相同大小的角度均匀地分割圆。然后对于每一方,它绘制线。这是一个很好的初学者程序来测试并使其工作,如果你不能完成基本的数学工作就不用担心,这些只是相当简单的三角表达式,这取决于传递给绘图方法的参数和辅助方法。