java rotate rectangle around the center

北战南征 提交于 2020-01-13 09:35:10

问题


I would like to rotate a rectangle around its center point and it should remain in the place that it is supposed be drawn and rotate in that space

this is my code:

AffineTransform transform = new AffineTransform();

    transform.rotate(Math.toRadians(45),rectangle.width/2, rectangle.height/2);
    Shape transformed = transform.createTransformedShape(rectangle);
    g2.fill(transformed)

the rectangle is rotated but it is drawn at a different part of the screen, how can I correct this?


回答1:


I haven't tried this, but it seems you aren't getting the correct middle of the rectangle. Try:

AffineTransform transform = new AffineTransform();
transform.rotate(Math.toRadians(45), rectangle.getX() + rectangle.width/2, rectangle.getY() + rectangle.height/2);
g2.fill(transformed);

The difference is now you're adding the width to the starting X point and adding the height to the starting Y point, hence the middle of the rectangle.

Hope this helps.




回答2:


AffineTransform transform = new AffineTransform();
transform.rotate(theta, rect.getX() + rect.width/2, rect.getY() + rect.height/2);
AffineTransform old = g2.getTransform();
g2.transform(transform);

// draw your rectangle here...

g2.setTransfrom(old);

If you do it like that, its possible to draw a more advanced rectangle. For example with a gradient fill, or text inside the rectangle. Everything will rotate with it.



来源:https://stackoverflow.com/questions/8807717/java-rotate-rectangle-around-the-center

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