当放大图像时,我需要计算视口的新位置.
UI的建立如下:
> ImagePanel绘制图像
> ImagePanelWrapper是围绕imagePanel的JPanel
> JScrollPane包含ImagePanelWrapper
放大或缩小时,ImagePanel的缩放系数将被更改,并且ImagePanel的首选大小正在重新计算.因此,即使ImagePanel保持在相同的视口点,此面板上的图像也会移动.
当用户按住CTRL并使用鼠标滚轮时,会调用以下方法.给定的点是MouseWheelListener提供的光标位置.通过这些方法的功能,当放大或缩小时,图像已经保持在相同的左上角位置.
问题是,我只是不知道如何相对于鼠标移动,例如Paint.NET.有任何想法吗?
/** * */ 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(); }
解决方法
如果这些假设是真的:
>提供的点相对于视口的左上角.
>视口的尺寸小于底层的ImagePanel.
然后可以调整视口,使光标在缩放操作之前和之后的图像超过同一点,如果以下列方式移动:
/** * */ 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(); }
这是数学的完整性: