简体   繁体   English

在 Java 的网格中旋转图像

[英]rotate image in grid in Java

Let's say I have a grid with images in Java.假设我在 Java 中有一个带有图像的网格。 I now draw the images in the Graphics2D component g as follows:我现在在 Graphics2D 组件 g 中绘制图像,如下所示:

  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.我现在有兴趣在给定方向上将图像(同时保持在相同的网格行和列中)旋转 90 度。 Could someone help me accomplish this?有人可以帮我完成这个吗?

First, you need a Graphics2D context.首先,您需要一个Graphics2D上下文。 In most cases when supplied with a Graphics it's actually an instance of Graphics2D so you can simply cast it.在大多数情况下,当提供Graphics时,它实际上是Graphics2D的一个实例,因此您可以简单地转换它。

Having said that though, when perform transformations, it's always useful to create a new context (this copies the state only)...话虽如此,但在执行转换时,创建新上下文总是有用的(这仅复制 state)...

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)...然后您可以围绕单元格的中心点旋转上下文(请记住, 0x0现在是我们的单元格偏移量)...

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您可能还想看看 The 2D Graphics trail ,因为您可以使用AffineTransformation代替,但它或多或少会完成同样的事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM