I need to calculate the new position of the viewport when zooming in to an image.
The UI is built up as follows:
If these assumptions are true:
Then the viewport can be adjusted so that the cursor is over the same point in the image before and after the zoom operation, if moved in the following manner:
/**
*
*/
public void zoomOut(Point point) {
this.imagePanel.setZoom(this.imagePanel.getZoom() * 0.9f);
Point pos = this.getViewport().getViewPosition();
int newX = (int)(point.x*(0.9f - 1f) + 0.9f*pos.x);
int newY = (int)(point.y*(0.9f - 1f) + 0.9f*pos.y);
this.getViewport().setViewPosition(new Point(newX, newY));
this.imagePanel.revalidate();
this.imagePanel.repaint();
}
/**
*
*/
public void zoomIn(Point point) {
this.imagePanel.setZoom(this.imagePanel.getZoom() * 1.1f);
Point pos = this.getViewport().getViewPosition();
int newX = (int)(point.x*(1.1f - 1f) + 1.1f*pos.x);
int newY = (int)(point.y*(1.1f - 1f) + 1.1f*pos.y);
this.getViewport().setViewPosition(new Point(newX, newY));
this.imagePanel.revalidate();
this.imagePanel.repaint();
}
Here's the math for completeness' sake:
You should be able to get the location of the mouse pointer using point.x
and point.y
- refer to the Point
documentation here. Accouding to the MouseMotionEvent
documentation here, the point.x
and point.y
are relative to the component under the mouse (the JScrollPane
).
You can incorporate these values into your calculation. Is this kinda what you were looking for?