I need to calculate the new position of the viewport when zooming in to an image.
The UI is built up as follows:
- ImagePanel draws the image
- ImagePanelWrapper is a JPanel wrapping around the imagePanel
- JScrollPane contains the ImagePanelWrapper
When zooming in or out, the ImagePanel's zoom factor is changed and the preferred size of the ImagePanel is being recalculated. Therefore the image on this panel moves, even though the ImagePanel stays at the same viewport point.
The following methods are called when the user holds down CTRL and uses the mouse wheel. The given point is the cursor location provided by the MouseWheelListener. With the functionality in these methods the image is already staying at the same top-left-position when zooming in or out.
The problem is that I just cant figure out how to move relative to the mouse, like Paint.NET for example. Any ideas?
/**
*
*/
public void zoomOut(Point point) {
this.imagePanel.setZoom(this.imagePanel.getZoom() * 0.9f);
Point pos = this.getViewport().getViewPosition();
int newX = (int) (pos.x * 0.9f);
int newY = (int) (pos.y * 0.9f);
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) (pos.x * 1.1f);
int newY = (int) (pos.y * 1.1f);
this.getViewport().setViewPosition(new Point(newX, newY));
this.imagePanel.revalidate();
this.imagePanel.repaint();
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…