Search code examples
javaalignmentcomponentstransformgraphics2d

Graphics2D Rotation Precision Issues


I am drawing 4 stacked rectangles, rotating the canvas about a point and then drawing that same shape again but the stacked rectangles aren't remaining completely aligned.

Here's a screenshot:

Alignment Issue

As you can see, the first, unrotated block is perfect but the following ones are misaligned. Why is this happening and how can I prevent it?


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);
    }
}

Solution

  • You need more precise stroke control:

    g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
    

    The default may let the geometry vary a bit, depending on the implementation. Pure tries to keep subpixel accuracy.