1、Image在窗體上拖拽,勢必會用到鼠標的三個事件(MouseDown,MouseUp,MouseMove),以左鍵爲例,PictureBox爲載體ide
Point mouseDownPoint = new Point(); //記錄拖拽過程鼠標位置 bool isMove = false; //判斷鼠標在picturebox上移動時,是否處於拖拽過程(鼠標左鍵是否按下) private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { mouseDownPoint.X = Cursor.Position.X; mouseDownPoint.Y = Cursor.Position.Y; isMove = true; } } private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { pictureBox1.Dock = DockStyle.None; if (e.Button == MouseButtons.Left) { isMove = false; } } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (isMove) { int x, y; int moveX, moveY; moveX = Cursor.Position.X - mouseDownPoint.X; moveY = Cursor.Position.Y - mouseDownPoint.Y; x = pictureBox1.Location.X + moveX; y = pictureBox1.Location.Y + moveY; pictureBox1.Location = new Point(x, y); mouseDownPoint.X = Cursor.Position.X; mouseDownPoint.Y = Cursor.Position.Y; } }
2、(1)鼠標滾輪------Image縮放(實現思路,靠設置PictureBox裏SizeModel屬性爲Zoom,改變PictureBox大小進行放縮,大圖片有卡頓,慢等問題,後續優化)優化
Bitmap myBmp; int zoomStep = 40; //縮放步長 //窗體加載事件 private void Form_Load(object sender, EventArgs e) { string filename = "圖片路徑+文件名(包括擴展名)" myBmp = new Bitmap(filename);//多種重載,基於本身的方式,將Image賦值與畫布 pictureBox1.Image = myBmp; pictureBox1.SizeMode = PictureBoxSizeMode.Zoom; //設置picturebox爲縮放模式 } //PictureBox控件綁定上鼠標中鍵事件 private void pictureBox1_MouseWheel(object sender, MouseEventArgs e) { int x = e.Location.X; int y = e.Location.Y; int ow = pictureBox1.Width; int oh = pictureBox1.Height; int VX, VY; if (e.Delta > 0) { pictureBox1.Width += zoomStep; pictureBox1.Height += zoomStep; PropertyInfo pInfo = pictureBox1.GetType().GetProperty("ImageRectangle", BindingFlags.Instance | BindingFlags.NonPublic); Rectangle rect = (Rectangle)pInfo.GetValue(pictureBox1, null); pictureBox1.Width = rect.Width; pictureBox1.Height = rect.Height; } if (e.Delta < 0) { if (pictureBox1.Width < myBmp.Width / 10) return; pictureBox1.Width -= zoomStep; pictureBox1.Height -= zoomStep; PropertyInfo pInfo = pictureBox1.GetType().GetProperty("ImageRectangle", BindingFlags.Instance | BindingFlags.NonPublic); Rectangle rect = (Rectangle)pInfo.GetValue(pictureBox1, null); pictureBox1.Width = rect.Width; pictureBox1.Height = rect.Height; } VX = (int)((double)x * (ow - pictureBox1.Width) / ow); VY = (int)((double)y * (oh - pictureBox1.Height) / oh); pictureBox1.Location = new Point(pictureBox1.Location.X + VX, pictureBox1.Location.Y + VY); }