Java: draw a circular spiral using drawarc

I'm doing a Java programming exercise. We must draw a circular spiral using the drawarc method so that the result looks similar to:

I have been studying this problem, which is what I have done so far:

import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.JFrame;

public class CircSpiral extends JPanel {
   public void paintComponent(Graphics g) {
      int x = 100;
      int y = 120;
      int width = 40;
      int height = 60;
      int startAngle = 20;
      int arcAngle = 80;
      for (int i = 0; i < 5; i++) {
         g.drawArc(x,y,width,height,startAngle,arcAngle);
         g.drawArc(x + 10,y + 10,startAngle + 10,arcAngle);
         x = x + 5;
         y = y + 5;
         startAngle = startAngle - 10;
         arcAngle = arcAngle + 10;
      }
   }

   public static void main(String[] args) {
      CircSpiral panel = new CircSpiral();
      JFrame application = new JFrame();
      application.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
      application.add(panel);
      application.setSize(300,300);
      application.setVisible(true);
   }
}

My code gives me this result:

I know the problem is my parameters to the drawarc method because the number is incorrect, but I don't know how to make the number loop Any help is appreciated thank you!

Solution

Your idea is almost right I made some changes You need to reverse the angle to draw the other side of the spiral and use the anchor to start the angle

import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.JFrame;

public class CircSpiral extends JPanel {

    public void paintComponent(Graphics g) {
        int x = getSize().width / 2 - 10;
        int y = getSize().height/ 2 - 10;
        int width = 20;
        int height = 20;
        int startAngle = 0;
        int arcAngle = 180;
        int depth = 10;
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {
                //   g.drawArc(x + 10,-arcAngle);
                //  x = x - 5;
                y = y - depth;
                width = width + 2 * depth;
                height = height + 2 * depth;
                g.drawArc(x,-arcAngle);
            } else {
                //  g.drawArc(x + 10,arcAngle);
                x = x - 2 * depth;
                y = y - depth;
                width = width + 2 * depth;
                height = height + 2 * depth;
                g.drawArc(x,arcAngle);
            }
        }
    }

    public static void main(String[] args) {
        CircSpiral panel = new CircSpiral();
        JFrame application = new JFrame();
        application.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
        application.add(panel);
        application.setSize(300,300);
        application.setVisible(true);
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>