Reset 2D Transformation?

If I do this:


g.translate(x, y);
g.rotate(a);

Then draw some images, the only way I know to undo/reset the transformations is to do the same thing in reverse with negative values.


g.rotate(-a);
g.translate(-x, -y);

Every once in a while images, that appear after I undo the transformations, that are not meant to be rotated, will flicker at an angle and with an offset. This leads me to believe that just doing a negative reverse isn’t working properly. Most of the time it’s fine, but it randomly happens a frame here and there.

So is there a (more) proper way to reset 2d transformations?

You talking about Slick2D I guess? If so, you can push the Transform and pop it too. you can also reset the transform via g.resetTransform(); :slight_smile:

No, just Graphics2D.


private LinkedList<Graphics> stack = new LinkedList<Graphics>();

public Graphics push(Graphics g) {
   this.stack.addFirst(g); // save it for later
   return g.create(); // copies the Graphic object
}

public Graphics pop() {
   return this.stack.removeFirst(); // restore it
}


public void paint(Graphics g) {
   ...
   g = this.push(g);
   ...
   g = this.pop();
   ...
}

You can also do;

public void paint(Graphics g)
{
    Graphics2D g2d=(Graphics2D)g;
    AffineTransform oldTransform=g2d.getTransform();

   ...

   g2d.setTransform(oldTransform);
}

The transformations are saved in the current AffineTransform of the Graphics object, so like SimonH said you can just get a copy of it and set it later.

@SimonH, Thanks. I haven’t seen the glitch since I applied your suggestion.