Eugene Yu
Eugene Yu

Reputation: 3958

Zoom in with affinetransform swing

I'm working on my personal project using JAVA swing.

The project is about drawing a map on a window.

enter image description here

The map is zoomable using affinetransform. The problem I'm having here is whenever I zoom in or out the map also shifts instead of zooming in/out on the point of the map that is at the center of the screen

private void updateAT()
{
    Dimension d = panel.getSize();
    int panelW = d.width;
    int panelH = d.height;

    Rectangle2D r = regionList[0].get("Victoria").getShape().getBounds2D();

    scaleX = (panelW/r.getWidth()) * zoom;
    scaleY = (panelH/r.getHeight()) * zoom;

    AffineTransform goToOrigin = AffineTransform.getTranslateInstance(-r.getMinX(), -r.getMinY());

    AffineTransform pan = AffineTransform.getTranslateInstance(panX, panY);

    AffineTransform scaleAndFlip = AffineTransform.getScaleInstance(scaleX, -scaleY);

    //AffineTransform mirror_y = new AffineTransform(1, 0, 0, -1, 0, panelH);

    AffineTransform centre = AffineTransform.getTranslateInstance(panelW/2, panelH/2);
    centre.translate(-((r.getWidth()*scaleX)/2), ((r.getHeight()*scaleY)/2));

    world2pixel.setToIdentity();
    //world2pixel.concatenate(mirror_y);
    world2pixel.concatenate(pan);
    world2pixel.concatenate(centre);
    world2pixel.concatenate(scaleAndFlip);
    world2pixel.concatenate(goToOrigin);
}

Upvotes: 2

Views: 3313

Answers (1)

trashgod
trashgod

Reputation: 205855

This example centers and scales a Shape, p3, by

  • translating a point of symmetry to the origin,

  • scaling the Polygon and then

  • translating back to the panel's center.

Note that the concatenated operations are performed in the (apparent) reverse of the declaration order, as discussed here.

at.setToIdentity();
at.translate(w / 2, h / 2);
at.scale(scale, scale);
at.translate(-p3x[5] + 10, -p3y[5]); 

Upvotes: 4

Related Questions