Java Graphics 2D-按鼠标位置缩放

ttp71kqs  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(156)

我有一个jpanel,我想使用鼠标滚轮来放大和缩小,但是我想缩放到鼠标的位置,这样鼠标下的点保持不变。我找到了一些questions here on stackoverflow,但是它们不适合我。
通过实现here所描述的内容,我已经非常接近于完成我想要做的事情了。

public class MyPanel extends JPanel {
...
    private double zoom = 1;
    private double zoom_old = 1;
    private int zoomPointX;
    private int zoomPointY;
...

   class CustomMouseWheelListener implements MouseWheelListener {
        @Override
        public void mouseWheelMoved(MouseWheelEvent e) {
            zoomPointX = e.getX();
            zoomPointY = e.getY();
            if (e.getPreciseWheelRotation() < 0) {
                zoom -= 0.1;
            } else {
                zoom += 0.1;
            }
            if (zoom < 0.01) {
                zoom = 0.01;
            }
            repaint();
        }
    }
...
    protected void paintComponent(Graphics g) {
        Graphics2D g2D = (Graphics2D) g;
        super.paintComponent(g2D);
        if (zoom != zoom_old) {
            double scalechange = zoom - zoom_old;
            zoom_old = zoom;
            double offsetX = -(zoomPointX * scalechange);
            double offsetY = -(zoomPointY * scalechange) ;
            AffineTransform at = new AffineTransform();
            at.scale(zoom, zoom);
            at.translate(offsetX, offsetY);
            g2D.setTransform(at);
        }
        a_different_class_where_i_do_some_drawing.draw(g2D);
    }

}

这几乎是我想要的。如果我尝试缩放,我注意到鼠标的位置被考虑在内,所以例如,如果我有我的鼠标在面板的左边,它会大致放大左边。但是,它没有完全放大到鼠标,所以鼠标下的点仍然改变。
有谁能帮我修修吗?
编辑:下面是上面发布的代码所发生的事情的图片:我先将鼠标放在蓝色方块上,然后用鼠标滚轮滚动。如您所见,鼠标位置如果改变:

h7appiyu

h7appiyu1#

我通过实现所描述的here解决了这个问题
下面是更新后的代码:

public class MyPanel extends JPanel {
...
    private double zoom = 1;
    private int zoomPointX;
    private int zoomPointY;
...

   class CustomMouseWheelListener implements MouseWheelListener {
        @Override
        public void mouseWheelMoved(MouseWheelEvent e) {
            zoomPointX = e.getX();
            zoomPointY = e.getY();
            if (e.getPreciseWheelRotation() < 0) {
                zoom -= 0.1;
            } else {
                zoom += 0.1;
            }
            if (zoom < 0.01) {
                zoom = 0.01;
            }
            repaint();
        }
    }
...
    protected void paintComponent(Graphics g) {
        Graphics2D g2D = (Graphics2D) g;
        super.paintComponent(g2D);
        AffineTransform at = g2D.getTransform();
        at.translate(zoomPointX, zoomPointY);
        at.scale(zoom, zoom);
        at.translate(-zoomPointX, -zoomPointY);
        g2D.setTransform(at);
        a_different_class_where_i_do_some_drawing.draw(g2D);
    }

}

相关问题