-2

我查找了如何在 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 定义为主体外部的私有静态变量

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

4

1 回答 1

1

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

于 2013-09-01T01:25:15.673 回答