我需要在其他方块内绘制一些正方形,但我不知道如何按照它们的中心旋转我的方块并使它们变小? 以下是最终应该如何显示的图片:
现在我有一些代码可以画出制作圆圈的方块。
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);
}
}
答案 0 :(得分: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);
}
}
});
}
}