C#在pictureBox上繪制直線


1.在pictureBox上添加鼠標響應事件:

this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown);
this.pictureBox1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseMove);

2.添加Bitmap作為畫布,用於保存圖形(窗體上繪制的圖形會因為刷新而消失):

 1         bool isDrawLine = false;
 2         Graphics g;
 3         Point p1, p2;
 4         Bitmap myImage;
 5         int PBwidth, PBheight;
 6         public Form1()
 7         {
 8             InitializeComponent();
 9             p1 = new Point();
10             p2 = new Point();
11             PBwidth = pictureBox1.Width; PBheight = pictureBox1.Height;
12             myImage = new Bitmap(PBwidth, PBwidth);
13             g = Graphics.FromImage(myImage);
14             g.Clear(Color.White);
15             pictureBox1.Image = myImage;
16         }

3.繪圖:

 1         private void dLine_Click(object sender, EventArgs e) //點擊繪制直線
 2         {
 3             isDrawLine = true;
 4         }
 5         private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
 6         {
 7             if (e.Button == MouseButtons.Left)
 8             {
 9                 if (isDrawLine == true)
10                 {
11                     if (p1.IsEmpty)
12                     {
13                         p1 = e.Location;
14                     }
15                     else
16                     {
17                         g.DrawLine(Pens.Black, p1, e.Location);
18                         pictureBox1.Image = myImage;
19                         isDrawLine = false;
20                         p1 = new Point(0, 0);
21                     }
22                 }
23             }
24             else if (e.Button == MouseButtons.Right)
25             {
26                 isDrawLine = false;
27                 g.DrawLine(Pens.White, p1, e.Location);
28                 pictureBox1.Image = myImage;
29                 p1 = new Point(0, 0);
30                 p2 = new Point(0, 0);
31             }
32         }
33         private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
34         {
35             if (isDrawLine && !p1.IsEmpty)
36             {
37                 g.DrawLine(Pens.White, p1, p2); 
38                 g.DrawLine(Pens.Black, p1, e.Location);
39                 pictureBox1.Image = myImage;
40                 p2 = e.Location;
41             }
42         }

 


免責聲明!

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



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