C# 中在圖像上畫框,通過鼠標來實現主要有四個消息響應函數MouseDown, MouseMove, MouseUp, Paint重繪函數實現。當鼠標鍵按下時開始畫框,鼠標鍵抬起時畫框結束。
Point start; //畫框的起始點 Point end,//畫框的結束點
bool blnDraw;//判斷是否繪制
Rectangel rect;
鼠標按下響應
private void PictureBox1_MouseDown(object sender, MouseEventArgs e) { start = e.Location; Invalidate(); blnDraw = true; }
鼠標移動響應
private void PictureBox1_MouseMove(object sender, MouseEventArgs e) { if (blnDraw) { if (e.Button != MouseButtons.Left)//判斷是否按下左鍵 return; Point tempEndPoint = e.Location; //記錄框的位置和大小 rect.Location = new Point( Math.Min(start.X, tempEndPoint.X), Math.Min(start.Y, tempEndPoint.Y)); rect.Size = new Size( Math.Abs(start.X - tempEndPoint.X), Math.Abs(start.Y - tempEndPoint.Y)); PictureBox1.Invalidate(); } }
鼠標鍵抬起響應
private void PictureBox1_MouseUp(object sender, MouseEventArgs e) { blnDraw = false; //結束繪制 }
重繪響應
private void imageBox1_Paint(object sender, PaintEventArgs e) { if (blnDraw) { if (imageBox1.Image != null) { if (rect != null && rect.Width > 0 && rect.Height > 0) { e.Graphics.DrawRectangle(new Pen(Color.Red, 3),rect);//重新繪制顏色為紅色 } } } }
注意:在繪制中如果導入的圖像的SizeMode為StretchImage時,畫框后圖像會縮放,導致框有可能不在pictureBox中,需要將PictureBox的FunctionMode 修改為Minimum 便可。