Graphics2D - Rotating Shapes on a Graphics2D Object

I have a Graphics2D object that I use to draw on my Canvas . I draw several shapes on Canvas and want to convert only one (or part) of them.

I will try to keep this simple:

 void render(Graphics2D g) { ... // Draw shape 1 ... // Draw shape 2 ... // Draw shape 3 } 

How do I rotate rotating figure 2, leaving form 1 and 3 intact? By β€œrotation” I mean rotation around its center point, which we can define as x and y for example.

I was looking for a way to do this for a while, but could not find anything that works the way I want.

Is there an easy way to do this?

+2
source share
3 answers

Instead of rotating the shape around its center point, rotate and then translate the canvas. To rotate the shape around the center of the figure (x, y) , first translate the canvas to (-x, -y) , and then rotate the canvas -d degrees and draw the shape as usual on (0,0).

When you are done, turn back and then translate back (note that with these geometric transformations, order is important, translation and then rotation will give you a completely different result).

This means that you can still draw an object at any turn without having to recalculate the coordinates yourself.

+5
source

To rotate a shape, use one of the Graphics2D.rotate methods.

Reset the transform used for both shape 1 and shape 3 . Before drawing shape 3 make sure you reset it to cached, since using rotate for shape 2 will change the current coordinates of the transformation.

Steps:

  • Convert Current Cache
  • Draw shape 1
  • Rotate
  • Draw shape 2
  • Set Convert to Cached
  • Draw shape 3
+2
source
  AffineTransform afx = new AffineTransform(); afx.rotate(angleRad, s.getCenter().x, s.getCenter().y); //afx.rotate(angleRad); java.awt.Shape ss = afx.createTransformedShape(s.getPrimativeShape()); return ss; 

s is my shell class for java.awt.Shape and does some things with it .... But what you want is on line 2. afx.rotate( Angle , xAnchorPoint ,yAnchorPoint); afx.rotate rotates an object around a point (xAnchorPoint; yAnchorPoint).

Hope this is what you wanted

+1
source

Source: https://habr.com/ru/post/1488895/


All Articles