2

我需要在另一个正方形内绘制一些正方形,但我不知道如何按它们的中心旋转我的正方形并使它们变小?这是最后应该是什么样子的图片:

在此处输入图像描述

现在我有一些代码可以绘制成圆形的正方形。

class MySquare  extends JComponent {
public void paint(Graphics g) {

    Graphics2D g2d = (Graphics2D) g;
    for (int i = 0; i < 20; i++) {

        g2d = (Graphics2D) g.create();
        g2d.rotate(Math.toRadians(45 - (i * 10)), 100, 100);

        // Difrent colors:
        if (i % 2 == 0)
            g2d.setColor(Color.black);
        else
            g2d.setColor(Color.green);
        g2d.fillRect(50, 50, 100, 100);

    }
    }
}

public class DrawRect {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 800, 800);
    window.getContentPane().add(new MySquare());
    window.setVisible(true);
  }
}
4

1 回答 1

7

您可以先在原点周围绘制图形(这很容易),然后翻译:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(400, 400);
        frame.setVisible(true);

        frame.add(new JPanel() {

            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2d = (Graphics2D) g;

                double alpha = Math.toRadians(5);
                double factor = 1 / (Math.sin(alpha) + Math.cos(alpha));
                double size = 200;

                g2d.translate(size, size);

                for (int i = 0; i < 20; i++) {
                    g2d.setColor(i % 2 == 0 ? Color.black : Color.green);

                    int intSize = (int) Math.round(size);

                    g2d.fillRect(-intSize / 2, -intSize / 2, intSize, intSize);

                    size = size * factor;

                    g2d.rotate(alpha);
                }
            }
        });
    }
}

截屏

于 2013-04-04T14:09:47.303 回答