簡體   English   中英

JScrollPane - 相對於鼠標位置進行縮放

[英]JScrollPane - Zoom relative to mouse position

我需要在放大圖像時計算視口的新位置。

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();
}

如果這些假設成立:

  • 提供的Point相對於視口的左上角。
  • 視口的尺寸小於底層的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();
}

這是完整性的數學:

在此輸入圖像描述

您應該能夠使用point.xpoint.y獲取鼠標指針的位置 - 請參閱此處Point文檔。 根據這里MouseMotionEvent文檔, point.xpoint.y是相對於鼠標下的組件( JScrollPane )。

您可以將這些值合並到計算中。 這有點像你在尋找什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM