Search code examples
javaswinggraphics2d

Line position after a rotation - Swing


I need to calculate the Cartesian equation of the orientation vector of a line. The user is free to rotate the point of view like this.


Point of view
Point of view


Point of view 2
Point of view 2


It would be easy if i knew two point of the line but i cannot retrieve the correct position after the rotation of the point, it seems the position of the line remains unchanged, i don't quite understand how the Graphics2D rotate works.Here is a chunk of the code.

g3.rotate(Math.toRadians(Double.valueOf(getJtfRotationAngle().getText()))
        ,eye.getEyePos().getX_pos()
        ,eye.getEyePos().getY_pos());

g3.setColor(Color.BLACK);

g3.draw(new Line2D.Double(eye.getEyePos().getX_pos(),eye.getEyePos().getY_pos()
        ,eye.getEyePos().getX_pos()+25,eye.getEyePos().getY_pos()));
g3.draw(new Line2D.Double(eye.getEyePos().getX_pos(),eye.getEyePos().getY_pos()
        ,eye.getEyePos().getX_pos(),eye.getEyePos().getY_pos()+25));

//This line is the orientation vector
g3.draw(new Line2D.Double(eye.getEyePos().getX_pos()
        ,eye.getEyePos().getY_pos()
        ,eye.getEyePos().getX_pos()+25
        ,eye.getEyePos().getY_pos()+25));

g3.drawOval((int)eye.getEyePos().getX_pos(),(int)eye.getEyePos().getY_pos(),10,10);
g3.fillOval((int)eye.getEyePos().getX_pos(),(int)eye.getEyePos().getY_pos(),10,10);

eye.setEyeTruePos(new Point(eye.getEyePos().getX_pos()-x_pos/2,eye.getEyePos().getY_pos()-y_pos/2));

Thanks in advance for your answer/explanation.


Solution

  • The rotate of the Graphics2D works like this:

    translate(x, y);
    rotate(theta);
    translate(-x, -y);
    

    So you apply the same transformations to your original line to get the two new points:

    tx=px+x;
    ty=py+y;
    rx=tx*Math.cos(a)-ty*Math.sin(a);
    ry=.....
    pnewx=rx-x;
    pnewy=ry-y;
    

    and the same for another point (px, py).