3

I have an Image on a JPanel. I'm then drawing a rectangle on top of the image like this:

Graphics2D image = (Graphics2D) g;
image.drawRect(......);
//create image code here.
image.rotate(1.5);
image.drawImage(....);

Problem is that when I rotate the image image.rotate(1.5), the rectangles stay in the same place.

I've tried creating the rectangle before rotating the image and after rotating the image, but both times it fails.

Is there an easy way to make the rectangles also rotate along with the image?

Thanks.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Marquinio
  • 4,601
  • 13
  • 45
  • 68
  • 1
    stupid question, but at which point do you draw the rectangle? Before or after the rotation. Your code does not specify. – Codemwnci Feb 14 '11 at 22:01

2 Answers2

1

One approach is to rotate the graphics context's affine transform, as shown in this example. In that way, all drawing will be rotated by the same amount.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • I was able to make my rectangles rotate along with the image, but how can I get a reference to the new rotated rectangle? I don't see a graphics2D.getShape(....). – Marquinio Feb 15 '11 at 15:35
  • Alternatively, you can use `createTransformedShape()`, as suggested here http://stackoverflow.com/questions/5006233 – trashgod Feb 15 '11 at 20:04
0

You might want to try using Rectangle, an implementation of the Rectangle2D class, then use g2d.draw(rectangle). This might be able to get the rotation state from the Graphics2D object better.

Community
  • 1
  • 1
Chris Dennett
  • 22,412
  • 8
  • 58
  • 84