免费的Java Swing组件,用于查看缩放+滚动的图像 - >



我似乎找不到一个Java Swing库,可以用来轻松地在JPanel中显示图像,并允许用户滚动,平移和缩放。有什么想法吗?谢谢。

我目前正在使用以下代码在 JPanel 中显示图像,但它非常基本。

我真的很想快速介绍缩放、滚动和平移功能。

    final BufferedImage img;
    try
    {
        img = ImageIO.read(image_file);
    }
    catch (IOException e)
    {
        throw new XCustomErrorClass("Could not open image file", e);
    }
    JPanel image_panel = new JPanel(new BorderLayout(0, 0)) 
    {
        protected void paintComponent(java.awt.Graphics g) 
        {
             super.paintComponent(g);
             g.drawImage(img.getScaledInstance(getWidth()-20,-1, Image.SCALE_FAST), 10, 10, this);
        };
    };

要滚动,请将面板放入JScrollPane中。

对于缩放和平移,您可以根据鼠标侦听器中维护的一些变量来转换 paintComponent 中的 Graphics2D 对象。像这样:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    // Backup original transform
    AffineTransform originalTransform = g2d.getTransform();
    g2d.translate(panX, panY);
    g2d.scale(zoom, zoom);
    // paint the image here with no scaling
    g2d.drawImage(img, 0, 0, null);
    // Restore original transform
    g2d.setTransform(originalTransform);
}

最新更新