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         }

猜你喜欢

转载自www.cnblogs.com/Ivy-yang/p/tuzi-bitmap-draw.html
今日推荐