Search code examples
javarotationgraphics2d

Rendering Rotated Images


Why is the following code not rendering the image at an angle. (I want the image to be rendered on an anchored point on the image). I think that it is rotating around the screen. How can I fix this?

public void drawWeapon(Graphics2D g) {
    int iconSize = main.SOutput.iconSize;
    int ePosX =(int) (getPosX() * iconSize 
                - (int) main.player.getPosX() *iconSize)/iconSize;
    int ePosY =(int) (getPosY() * iconSize 
                - (int) main.player.getPosY() *iconSize)/iconSize;

    int PosX = ePosX + (main.SOutput.resX/2)*iconSize 
                + main.SOutput.xPaddingSide;
    int PosY = ePosY + (main.SOutput.resY/2)*iconSize 
                - getImageSizeY()*iconSize;

    if (inventory[0][main.gui.itemSelected] != null){
    g.rotate(facingLeft?scincePressed:-scincePressed);
    g.drawImage(inventory[0][main.gui.itemSelected].item.getImage(), 
                 PosX + (facingLeft?0:getImageSizeX() * iconSize/2), PosY +
                 (getImageSizeY() * iconSize/2), getImageSizeX() * iconSize/2,
                 getImageSizeY() * iconSize/3, null);
    g.rotate(facingLeft?-scincePressed:scincePressed);
    }
}

Solution

  • You should use this way of working:

    1. Push the matrix
    2. Translate to the point of rotation
    3. Rotate
    4. Render at (0, 0)
    5. Pop matrix

    In code, it would be:

    AffineTransform matrix = g.getTransform();
    g.translate(originX, originY);
    g.rotate(angle);
    g.drawImage(0, 0, ...);
    g.setTransform(matrix);
    

    You might also try Graphics2D.rotate(theta, originX, originY);