Search code examples
javarotationgeometrylinear-algebragraphics2d

How can I get a Point on a rotated image?


With an image drawn with Graphics2D, I need to access the bottom left corner's coordinates (Or any of the other 3 points on the image). The problem is that the image is rotated. Here is the paintComponent() method:

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;

    //Makes a white background
    g2d.setColor(Color.WHITE);
    g2d.fill(new Rectangle2D.Float(0, 0, (float)Toolkit.getDefaultToolkit().getScreenSize().getWidth(), (float)Toolkit.getDefaultToolkit().getScreenSize().getHeight()));

    //Draws Images & rotates
    g2d.rotate(Math.toRadians(rocketAngle), r.getxPos() + (r.getImage().getWidth()/2), r.getyPos());
    g2d.drawImage(r.getImage(), r.getxPos(), r.getyPos(), this);
}

(Where 'r' is an object that contains a photo)

Normally, I would add the images height to the images drawing point, but this doesn't work because the image is rotated. Does anyone know how to accomplish this?


Solution

  • So you have the following points in your original coordinate system (CS1):

    CS1:
    Left bottom: lb(0, h)
    Right bottom: rb(w, h)
    Right top: rt(w, 0)
    Left top: lt(0, 0)
    

    You want to rotate picture around point v(w/2, 0). For this let's introduce new coordinate system with center at point v (CS2):

    CS2:
    x' = x-w/2
    y' = y
    

    Now let's introduce CS3 which is CS2 rotated on angle phi:

    CS3:
    x'' = x'*cos phi - y'*sin phi = (x-w/2)*cos phi - y*sin phi
    y'' = x'*sin phi + y'*cos phi = (x-w/2)*sin phi + y*cos phi
    

    Now you want to get coordinates of points lb, rb, rt, lt of CS1 in CS3:

    lb'' = (-(w/2)*cos phi - h*sin phi, -(w/2)*sin phi + h*cos phi)
    

    I hope, you got the idea