请告诉我如何画一个方形螺旋?一开始我试着用线条来画,但不太成功,也许是这个图的公式?目前我在正方形的帮助下绘制,但结果不是我需要的。
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Line2D;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Spiral {
private static JFrame frame;
private static int x, x2;
private static int y, y2;
private static int x1;
private static int y1;
private static int n;
private static int step;
private static Line2D.Double line = null;
public Spiral(){
x = 300;
y = 200;
x2 = 400;
y2 = 200;
step = 30;
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number: ");
n = Integer.parseInt(reader.readLine()) ;
frame = new JFrame("Spiral");
frame.setSize(600,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GraphicsComponent gc = new GraphicsComponent();
frame.add(gc);
frame.setVisible(true);
}
static class GraphicsComponent extends JComponent {
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
x1 = 250;
y1 = 50;
int size = n * n;
for (int i = 0; i < n; i++) {
Rectangle rectangle = new Rectangle(x1, y1, size, size);
size -= 10;
x1 += 5;
y1 += 5;
g2.draw(rectangle);
}
/*
int dir = 0;
for (int i = 1; i <= 6; i++) {
if (dir == 0){
line = new Line2D.Double(x, y, x2 ,y2);
drawLine(g2);
dir++;
}
else if(dir == 1){
x = x2;
y = y;
x2 = x2;
y2 += STEP;
line = new Line2D.Double(x, y, x2 ,y2);
drawLine(g2);
dir++;
}
else if(dir == 2){
x = y2 + STEP;
y = y2;
x2 -= 0;
y2 = y2;
line = new Line2D.Double(x, y, x2 ,y2);
drawLine(g2);
dir++;
}
else if(dir == 3){
x = x;
y = y;
x2 = x;
y2 -= STEP;
line = new Line2D.Double(x, y, x2 ,y2);
drawLine(g2);
dir++;
}
else if(dir == 4){
x = x;
y = y;
x2 = x;
y2 -= STEP;
line = new Line2D.Double(x, y, x2 ,y2);
drawLine(g2);
dir++;
}
else if(dir == 5){
x = x;
y = y2;
x2 += STEP;
y2 = y;
line = new Line2D.Double(x, y, x2 ,y2);
drawLine(g2);
dir = 1;
}
}
*/
}
}
private static void drawLine(Graphics2D g2){
g2.setColor(Color.RED);
g2.fill(line);
g2.draw(line);
}
}
此处借用 Swing 中的画线,算法本身也不是很复杂:螺旋边的长度
dist
每两步增加一个固定的量step
。