Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java rotate rectangle around the center

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?

like image 575
trs Avatar asked Jan 10 '12 17:01

trs


1 Answers

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.

like image 128
Dan W Avatar answered Sep 20 '22 03:09

Dan W