views:

556

answers:

1

I've got a JPanel I'm drawing onto and I'm trying to get it so that you can use the mouse wheel to "zoom" in and out by modifying the variable scale. Right now what happens is you can zoom in or out but all of the drawing shifts to the right and downwards when you zoom in and then back up and left when zooming out.

I want to make it so that it adjusts as if you were zooming in on the point at the center of the JPanel but I can't figure out how to calculate the right offset to translate by…

Anybody got an idea of how to do this, or even better a cleaner way of achieving this whole pan and zoom ability?

I am basically plotting a bunch of coordinates that came from a system where 0,0 is in the lower left corner and fall between the bounds:

xMin = 661208
xMax = 662618

yMin = 4291657
yMax = 4293285

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D) g;

    double scale = details.getScale();
    double xOffset = details.getxOffset();
    double yOffset = details.getyOffset();

    g2.scale(scale, -scale);

    // Dividing offset by scale makes panning 1:1 with the cursor still. yMax to account for the
    // fact we needed to flip around the y axis to make it right-side up.
    g2.translate((-xMin + xOffset / scale), (-yMax + yOffset / scale));

    // Code to draw stuff goes here.  It uses coordinates between xMin-xMax and yMin-yMax to draw.
    .
    .
    .
}
+2  A: 

This question might help you http://stackoverflow.com/questions/690871/affinetransform-scaling-a-shape-from-its-center

Pierre