日期:2014-05-20  浏览次数:20805 次

图片的拖动受范围限制,如何解决
图片在固定大小的矩形框里显示,对图片放大后,可以进行拖动、或缩小,但是不能让矩形框的底板露出来

(用矩阵进行变换,缩放是等倍的

请问,有什么简单的方法吗?

比如下面这段代码,怎样加上拖放的范围控制呢?(图片放大到一定程度后把Panel全部覆盖,但是在移动的过程中不能把图片的边界一处JPanel的边界)
[code=Java][/code]

package map;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class Layer extends JPanel{
  private static final long serialVersionUID = 1L;
  ImageIcon img = new ImageIcon(Toolkit.getDefaultToolkit().createImage("/root/桌面/2000.jpg"));
   
  //以下两个参数描述图层的位置
  private int x = 0;//
  private int y = 0;
  //以下两个参数描述图层的大小
  private int width = 300;
  private int height = 300;
   
  //以下两个参数描述图层的每次放大或缩小的尺寸
  private int dx = 50;
  private int dy = 50;
   
  public Layer(){
  this.addMouseWheelListener(new MouseWheelListener() {
   
  public void mouseWheelMoved(MouseWheelEvent e) {
  if(e.getWheelRotation() < 0){
  zoom();
  }else{
  reduce();
  }
   
  }
  });
   
  MouseAdapter ma = new MouseAdapter(){

  @Override
  public void mouseClicked(MouseEvent e) {
  zoom();
  }


  boolean moveEnable = false;
  Point point1 = null;
  Point point2 = null;
   
  @Override
  public void mousePressed(MouseEvent e) {
  moveEnable = true;
  point1 = e.getPoint();
  }

  @Override
  public void mouseReleased(MouseEvent e) {
  moveEnable = false; 
  point1 = null;
  point2 = null;
  }

  @Override
  public void mouseMoved(MouseEvent e) {
  //System.out.println("move");
  }
  @Override
  public void mouseDragged(MouseEvent e) {
  System.out.println("dragged");
  point2 = e.getPoint();
  if(moveEnable){
  if(point1 != null && point2 != null){
  int dx = point2.x - point1.x;
  int dy = point2.y - point1.y;
  x = x + dx;
  y = y + dy;
  //Layer.this.setLocation(_x, _y);
  point1 = point2;
  repaint();
  }
  }
  }
  };
   
  this.addMouseMotionListener(ma);
  this.addMouseListener(ma);
  }
  @Override
  public void paint(Graphics g) {