Graphics2D Rotation Precision Issues

删除回忆录丶 提交于 2019-12-11 06:37:31

问题


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:

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

回答1:


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.



来源:https://stackoverflow.com/questions/18271976/graphics2d-rotation-precision-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!