Question

I have a Graphics2D object which I use to draw on my Canvas. I draw multiple shapes on the Canvas and want to transform only one (or part) of them.

I'll try to keep this simple:

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

How would I go about rotating shape 2 while leaving shape 1 and 3 intact? By "rotate" I mean rotating around its center point, which we can define as x and y for example.

I've been looking for a way to do this for a while now, but couldn't find anything that works the way I want it to.

Is there any simple way to do this?

Was it helpful?

Solution

Rather than rotating the shape around it's centre point, rotate and then translate the canvas. To rotate around the centre of the shape at (x, y), first translate the canvas by (-x, -y) and then rotate the canvas -d degrees and draw the shape as normal at (0,0).

When you're done, rotate back then translate back (note that with these geometric transformations the order is important, translating and then rotating will give you a completely different outcome).

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

OTHER TIPS

In order to rotate a shape, use one of the Graphics2D.rotate methods.

Cache the transform used for both shape 1 and shape 3. Before drawing shape 3, ensure that you reset the transform to the cached one, since using rotate for shape 2 will alter the current transform coordinates.

Steps:

  1. Cache current transform
  2. Draw shape 1
  3. Rotate
  4. Draw shape 2
  5. Set transform to cached one
  6. Draw shape 3
    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 wrapper class for java.awt.Shape and does some stuff with it.... But what you want is in line 2. afx.rotate(Angle,xAnchorPoint,yAnchorPoint); afx.rotate rotates the object about the point (xAnchorPoint;yAnchorPoint).

Hope this is what you wanted

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top