【问题标题】:Code to draw a star绘制星星的代码
【发布时间】:2013-09-04 10:42:33
【问题描述】:

我查了一下如何用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 被定义为身体外部的私有静态变量

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

【问题讨论】:

  • 特别是什么问题?似乎用笔和纸“玩电脑”就足以完成数学。

标签: java awt paint java-2d


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    相关资源
    最近更新 更多