Home > Blockchain >  rotate image in grid in Java
rotate image in grid in Java

Time:12-30

Let's say I have a grid with images in Java. I now draw the images in the Graphics2D component g as follows:

  g.drawImage(image, 50 * cellWidth, 50 * cellHeight, cellWidth, cellHeight, Color.WHITE, null)

I'm now interested in rotating the image (while staying in the same grid row and column) 90 degrees in a given direction. Could someone help me accomplish this?

CodePudding user response:

First, you need a Graphics2D context. In most cases when supplied with a Graphics it's actually an instance of Graphics2D so you can simply cast it.

Having said that though, when perform transformations, it's always useful to create a new context (this copies the state only)...

Graphics2D g2d = (Graphics2D) g.create();

Next, you want to translate the origin point. This makes it a lot easier to do things like rotation.....

g2d.translate(50 * cellWidth, 50 * cellHeight);

Then you can rotate the context around the centre point of the cell (remember, 0x0 is now our cell offset)...

g2d.rotate(Math.toRadians(90), cellWidth / 2, cellWidth / 2);

And then we can simply draw the image...

g2d.drawImage(image, 0, 0, cellWidth, cellHeight, Color.WHITE, null);

And don't forget to dispose of the copy when you're done

g2d.dispose();

You might also want to take a look at The 2D Graphics trail, as you could use a AffineTransformation instead, but it'd be accomplishing the same thing, more or less

  •  Tags:  
  • java
  • Related