Search code examples
javaswingaffinetransform

Zoom and Pan JPanel with multiple Images drawn on it


I am drawing a tile map, where I draw a different 64x64 pixel image for every tile, and each tile object draws itself.

I also have a player object and zombie objects that also draw themselves. the player and zombie objects have their own affine transform instantiation that modify the g.drawImage I call for each one.

My question is. how would I implement a 'camera' that I can zoom and pan with, to see only the part of the map inside the JPanel?


Solution

  • What I would do is start with a BufferedImage which will act as the final output.

    Create it so it's size is width x scale and height x scale.

    Obtain a Graphics context from it using BufferedImage#createGraphics and set the context's scale accordingly, using Graphics#scale.

    Then paint the output to this Graphics context, don't forget to call Graphics#dispose when you're done.

    With this BufferedImage, render this to the screen. This gives you the "zoom" functionality.

    For the panning, you can take a look at Java Applet Game 2D Window Scrolling for an example.