java - 使用鼠标和图形缩放

标签 java swing awt zooming

我在我的 JComponent 中绘制了一些曲线等......使用 Graphics G(不是 2D)。

现在我想使用鼠标的滚轮来放大和缩小。

有轨道吗?

我听说过有关 BuferredImage 的讨论?

最佳答案

您需要考虑一些注意事项...

最终结果将取决于您想要实现的目标。如果您使用 Graphics2D API 绘制曲线,则每次渲染组件时简单地缩放坐标可能会更简单。您需要确保比例的任何变化都反射(reflect)在组件本身的首选尺寸中。

例如,您还可以将“默认”输出渲染到 BufferedImage 并简单地使用 AffineTransform 更改用于渲染结果的缩放比例。

这个简单的使用 BufferedImage 并从磁盘加载图片,但基本概念是相同的。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseWheelEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ZoomPane {

    public static void main(String[] args) {
        new ZoomPane();
    }

    public ZoomPane() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(new TestPane()));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private BufferedImage img;
        private float scale = 1;

        public TestPane() {
            try {
                img = ImageIO.read(new File("/path/to/image"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            addMouseWheelListener(new MouseAdapter() {

                @Override
                public void mouseWheelMoved(MouseWheelEvent e) {
                    double delta = 0.05f * e.getPreciseWheelRotation();
                    scale += delta;
                    revalidate();
                    repaint();
                }

            });
        }

        @Override
        public Dimension getPreferredSize() {            
            Dimension size = new Dimension(200, 200);
            if (img != null) {            
                size.width = Math.round(img.getWidth() * scale);
                size.height = Math.round(img.getHeight() * scale);                
            }        
            return size;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (img != null) {
                Graphics2D g2d = (Graphics2D) g.create();
                AffineTransform at = new AffineTransform();
                at.scale(scale, scale);
                g2d.drawImage(img, at, this);
                g2d.dispose();
            }
        }
    }

}

您还可以缩放直接传递给 paintComponent 方法的 Graphics 上下文。

这里重要的是记得在完成后重置AffineTransform,否则它会在渲染时传递给其他组件,而不会产生预期的输出...

这个例子基本上创建了 Graphics 上下文的副本,我们可以在不影响原始内容的情况下对其进行操作和处理,使其更易于处理

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseWheelEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Path2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ZoomPane {

    public static void main(String[] args) {
        new ZoomPane();
    }

    public ZoomPane() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(new TestPane()));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private float scale = 1;

        public TestPane() {
            addMouseWheelListener(new MouseAdapter() {

                @Override
                public void mouseWheelMoved(MouseWheelEvent e) {
                    double delta = 0.05f * e.getPreciseWheelRotation();
                    scale += delta;
                    revalidate();
                    repaint();
                }

            });
        }

        @Override
        public Dimension getPreferredSize() {
            Dimension size = new Dimension(200, 200);
            size.width = Math.round(size.width * scale);
            size.height = Math.round(size.height * scale);
            return size;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            AffineTransform at = new AffineTransform();
            at.scale(scale, scale);
            g2d.setTransform(at);

            g2d.setColor(Color.RED);

            // This is for demonstration purposes only
            // I prefer to use getWidth and getHeight
            int width = 200;
            int height = 200;

            Path2D.Float path = new Path2D.Float();
            int seg = width / 3;
            path.moveTo(0, height / 2);
            path.curveTo(0, 0, seg, 0, seg, height / 2);
            path.curveTo(
                    seg, height, 
                    seg * 2, height, 
                    seg * 2, height / 2);
            path.curveTo(
                    seg * 2, 0, 
                    seg * 3, 0, 
                    seg * 3, height / 2);

            g2d.draw(path);


            g2d.dispose();
        }
    }
}

看看Transforming Shapes, Text and Images了解更多详情

关于java - 使用鼠标和图形缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19643637/

相关文章:

java - 无法根据第一个微调器值获取第二个微调器值

java - 在java中跟踪鼠标移动

java - 在 Java 中垂直翻转原始图像

java - Java DataBuffer 类的原因是什么?

java - 如何获取运行时间较短的 Java 进程的线程转储

java - 如何获得 Joda DateTime 时区的冒号?

java - Docx4J Bad [Content_Types].xml 与 WebLogic 12c

java - 防止文本位于边框对象后面

java - MouseListener 被另一个 JPanel 组件掩盖了

java - JFrame 的比例调整大小