C# PictureBox 的圖像上使用鼠標畫矩形框


C# 中在圖像上畫框,通過鼠標來實現主要有四個消息響應函數MouseDown, MouseMove, MouseUp, Paint重繪函數實現。當鼠標鍵按下時開始畫框,鼠標鍵抬起時畫框結束。

1 Point start; //畫框的起始點
2 Point end,//畫框的結束點<br>bool blnDraw;//判斷是否繪制<br>Rectangel rect;

鼠標按下響應

1 private void PictureBox1_MouseDown(object sender, MouseEventArgs e) 2 { 3       start = e.Location; 4  Invalidate(); 5       blnDraw = true; 6 }

 鼠標移動響應

 1 private void PictureBox1_MouseMove(object sender, MouseEventArgs e)  2 {  3     if (blnDraw)  4  {  5         if (e.Button != MouseButtons.Left)//判斷是否按下左鍵
 6             return;  7         Point tempEndPoint = e.Location; //記錄框的位置和大小
 8         rect.Location = new Point(  9  Math.Min(start.X, tempEndPoint.X), 10  Math.Min(start.Y, tempEndPoint.Y)); 11         rect.Size = new Size( 12         Math.Abs(start.X - tempEndPoint.X), 13         Math.Abs(start.Y - tempEndPoint.Y)); 14  PictureBox1.Invalidate(); 15  } 16 }       

鼠標鍵抬起響應

private void PictureBox1_MouseUp(object sender, MouseEventArgs e) { blnDraw = false; //結束繪制
 }

重繪響應

 1 private void imageBox1_Paint(object sender, PaintEventArgs e)  2 {  3      if (blnDraw)  4  {  5          if (imageBox1.Image != null)  6  {  7              if (rect != null && rect.Width > 0 && rect.Height > 0)  8  {  9                   e.Graphics.DrawRectangle(new Pen(Color.Red, 3),rect);//重新繪制顏色為紅色
10  } 11  } 12  } 13  
14 }

注意:在繪制中如果導入的圖像的SizeMode為StretchImage時,畫框后圖像會縮放,導致框有可能不在pictureBox中,需要將PictureBox的FunctionMode 修改為Minimum 便可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM