开发者

rotate shape java2d without losing its origin

开发者 https://www.devze.com 2022-12-12 09:14 出处:网络
protected void paintComponent(Graphics g) { Graphics2D gr = (Graphics2D) g.create(); // draw Original image
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开发者_如何学JAVA,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


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   ]


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


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?)

0

精彩评论

暂无评论...
验证码 换一张
取 消