我正在绘制 4 个堆叠的矩形,围绕一个点旋转画布,然后再次绘制相同的形状,但堆叠的矩形没有保持完全对齐。
这是一个屏幕截图:
如您所见,第一个未旋转的块是完美的,但后面的块未对齐。为什么会发生这种情况,我该如何预防?
SSCE
//Just import everything to keep it short and sweet
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class AlignmentIssue extends JComponent {
@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
double angle = Math.toRadians(30);
int numRects = (int)Math.floor(2.0 * Math.PI / angle);
Rectangle rect = new Rectangle(0, 100, 20, 25);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.translate(getWidth() / 2, getHeight() / 2);
for(int i = 0; i < numRects; ++i) {
AffineTransform transform = g2d.getTransform();
for(int n = 0; n < 3; ++n) {
g2d.draw(rect);
g2d.translate(0, rect.height);
}
g2d.setTransform(transform);
g2d.rotate(angle);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Alignment Issue");
frame.add(new AlignmentIssue());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(800, 600));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}