[英]Retain relative mouse position while resizing a JPanel in a JScrollPane
[英]JScrollPane - Zoom relative to mouse position
我需要在放大圖像時計算視口的新位置。
UI構建如下:
放大或縮小時,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();
}
如果這些假設成立:
然后可以調整視口,以便在縮放操作之前和之后光標位於圖像中的同一點上,如果按以下方式移動:
/**
*
*/
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();
}
這是完整性的數學:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.