Java GUI Rotation and Translation of Rectangle

泪湿孤枕 提交于 2019-12-05 16:57:37
trashgod

One of two approaches are commonly used:

  • Rotate the graphics context around the center (x, y) of the Shape, as shown here.

    rotate(double theta, double x, double y)
    
  • Translate to the origin, rotate and translate back, as shown here.

    g2d.translate(this.getWidth() / 2, this.getHeight() / 2);
    g2d.rotate(theta);
    g2d.translate(-image.getWidth(null) / 2, -image.getHeight(null) / 2);
    

Note the apparent reverse order of concatenation in the second example.

Addendum: Looking more closely at your example, the following change rotates the Rectangle around the panel's center.

g2d.rotate(theta, getWidth() / 2, getHeight() / 2);

Also, use the @Override annotation, and give your panel a reasonable preferred size:

@Override
public Dimension getPreferredSize() {
    return new Dimension(640, 480);
}

Use affine transform to rotate the rectangle and convert it into the rotated polynomial. Check the code below:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(Color.white);
    /* rotate rectnagle around rec.x and rec.y */
    AffineTransform at = AffineTransform.getRotateInstance(theta, 
        rec.x, rec.y);
    /* create the plunomial */
    Polygon p = new Polygon();
    /* path interator of the affine transformed polynomial */
    PathIterator i = rec.getPathIterator(at);
    while (!i.isDone()) {
        double[] points = new double[2];
        i.currentSegment(points);
        p.addPoint((int) points[0], (int) points[1]);

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