我很乐意请求您帮助处理涉及使用栅格和矢量数据(由线条表示)的缩放操作的代码。很抱歉有一个完整的代码,稍长一点:
public class ZoomOperations extends JPanel {
private java.awt.image.BufferedImage image = null;
private Line2D.Double line = null;
private double scale = 1.0, sx = 0.0, sy = 0.0;
private int ratio = 20;
private MouseManager manager = null;
public ZoomOperations() throws IOException {
line = new Line2D.Double();
image = javax.imageio.ImageIO.read(new java.io.File("E:\\test.jpg"));
manager = new MouseManager(this);
addMouseListener(manager);
addMouseMotionListener(manager);
addMouseWheelListener(manager);
}
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
AffineTransform trans = g2.getTransform();
double x = 0.5*(getWidth() - scale * image.getWidth());
double y = 0.5*(getHeight() - scale * image.getHeight());
g2.translate(x, y);
g2.scale(scale, scale);
g2.drawImage(image, 0, 0, this);
g2.setTransform(trans); //Incorrect line?
g2.draw(line);
}
public void setPoints(Point start, Point end) { line.setLine(start, end); repaint();}
public void ZoomPlus() {scale = (++ratio + 2) / 10.0; repaint();}
public void ZoomMinus(){scale = (--ratio + 2) / 10.0; repaint();}
class MouseManager extends MouseAdapter {
ZoomOperations item;
Point start;
public MouseManager(ZoomOperations item_){item = item_;}
public void mousePressed(MouseEvent e){start = e.getPoint();}
public void mouseDragged(MouseEvent e){Point end = e.getPoint();
item.setPoints(start, end);
item.repaint();
}
public void mouseWheelMoved(MouseWheelEvent e){
int notches = e.getWheelRotation();
if (notches < 0) ZoomPlus();
else ZoomMinus();
}
}
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ZoomOperations zoom = new ZoomOperations();
frame.add(zoom);
frame.setSize(new Dimension(800, 600));
frame.setVisible(true);
}
}
不幸的是,缩放操作仅适用于栅格数据。矢量线保持其位置和大小。
没有缩放的初始数字:
应用缩放加操作:
在我看来,以下行可能不正确
g2.setTransform(trans);
不涉及累积的移位x,y和比例......但是,错误可能在其他地方: - )
另一个问题:是否有更简单的方法在Java中实现缩放操作?非常感谢你的帮助...