soField
soField

Reputation: 2696

rotate shape java2d without losing its origin

protected void paintComponent(Graphics g) {
    Graphics2D gr = (Graphics2D) g.create();
    // draw Original image
    super.paintComponent(gr);

    // draw 45 degree rotated instance
    int aci=-45;
    gr.transform(AffineTransform.getRotateInstance(Math.toRadians(aci)));
    super.paintComponent(gr);

    //translate rotated instance from origin to +10 on y axes
    gr.translate(0,10);
    super.paintComponent(gr);
}

But what if I want to draw the rotated shape at its original image origin.

I mean I want to rotate shape its origin without sliding

Upvotes: 1

Views: 4656

Answers (3)

Diego Dias
Diego Dias

Reputation: 22646

To rotate your image through an specific origin use

x2 = cos(angle)*(x1 - x0) -sin(angle)*(y1 - y0) + x0

y2 = sin(angle)*(x1 - x0) + cos(angle)*(y1 - y0) + y0

Where (x0,y0) is the origin you want.

To do it easier just use the matrix notation

 [x2    [cos -sin x0   [x1 - x0  
  y2 =   sin cos  y0    y1 - y0
  1]      0   0    1]      1   ]

Upvotes: 2

jprete
jprete

Reputation: 3759

When you do this sort of thing, you have to remember that you are never moving anything that's been drawn. You are only moving the paint brush, so to speak.

You'd typically do something along these lines:

  1. Translate the drawing origin to the point where you want to draw.
  2. Rotate the paint brush to the angle that you want to paint at.
  3. Paint the object.
  4. Reverse your old transforms so that future objects are not affected.

I can't, however, remember the right order to do the translate and rotate in. (Any commentary out there?)

Upvotes: 0

Bart van Heukelom
Bart van Heukelom

Reputation: 44114

First, a tip. Instead of gr.transform(blablabla); I think you can use gr.rotate(angle);.

I'm not sure what you're precisely doing here, but the usual way to accomplish rotation around a point is:

  • Translate by that point's x and y (not sure about positive or negative...try both)
  • Rotate
  • Translate back

Upvotes: 0

Related Questions