Java 绘制星星的代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18554303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:00:40  来源:igfitidea点击:

Code to draw a star

javaawtpaintjava-2d

提问by user2578330

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

我查了下如何用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 is defined as a private static variable outside the body

halfPI 被定义为 body 之外的私有静态变量

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

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

回答by Niklas

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.

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