如何使用单位圆触发在Java中绘制环形

时间:2018-06-29 23:56:21

标签: java loops graphics awt trigonometry

我必须使用Java中的线条(drawLine)绘制一个环,该环应该看起来像所附的图片。我们提供了hereDrawingPanel

我使用线制作了一个规则的圆,但是我不确定如何获得圆环形状。我是编程的新手,这是我的第一篇文章,如果我错过了一些重要的事情,就此道歉。

到目前为止,这是我的代码:

public static int panelSize = 400;
    public static void drawCircle()
    {
    double radius = 200;
    int x2 = 200;
    int y2 = 200;

    DrawingPanel dp = new DrawingPanel(panelSize, panelSize);
    dp.setBackground(Color.CYAN);

    Graphics dpGraphics = dp.getGraphics(); 
    dpGraphics.setColor(Color.RED);

    for (int circle = 0; circle <= 360; circle++)
    {
        int x = (int)(x2 + Math.sin(circle * (Math.PI / 180)) * radius);
        int y = (int)(y2 + Math.cos (circle * (Math.PI / 180)) * radius);

        dpGraphics.drawLine(x, y, x2, y2);
    }
}

这是最终结果应为:

https://i.stack.imgur.com/FXInb.png

1 个答案:

答案 0 :(得分:0)

可以通过从一个点到圆上更远的点画一条线,多次经过起始点来绘制这样的图形。

这是我想出的:

// Radius
int radius = 200;
// center of the circle
int centerX = 300, centerY = 300;

// The number of edges. Set to 5 for a pentagram
int mod = 136;
// The number of "points" to skip - set to 2 for a pentagram
int skip = 45;

// Precalculated multipier for sin/cos
double multi = skip * 2.0 * Math.PI / mod; 

// First point, calculated by hand
int x1 = centerX; // sin(0) = 0
int y1 = centerY + radius; // cos(0) == 1

for (int circle = 1; circle <= mod; circle++)
{
    // Calculate the end point of the line.
    int x2 = (int) (centerX + radius * Math.sin(circle * multi));
    int y2 = (int) (centerY + radius * Math.cos(circle * multi));
    dpGraphics.drawLine(x1, y1, x2, y2);
    // Next start point for the line is the current end point
    x1 = x2;
    y1 = y2;
}

结果如下:

Example code, overloaded java.swing.Frame.paint(java.awt.Graphics g)