C# Winform画线

在Winform中实现的效果如下:

 

WPF画线参考:C# WPF画线 - 十年新 - 博客园 (cnblogs.com)

代码请参考:

 1 using System.Drawing;
 2 using System.Drawing.Drawing2D;
 3 using System.Windows.Forms;
 4 
 5 namespace DrawLineDemo
 6 {
 7     public partial class Form1 : Form
 8     {
 9         public Form1()
10         {
11             InitializeComponent();
12         }
13 
14         public Point PointStart, PointEnd;//定义连线之间的两点,PointStart:起始点;PointEnd:结束点;
15         public int Flag = 0;
16 
17         private void Form1_MouseUp(object sender, MouseEventArgs e)
18         {
19             Flag = 0;
20         }
21 
22         private void Form1_MouseMove(object sender, MouseEventArgs e)
23         {
24             Text = "Location:X=" + e.X.ToString() + ",Y=" + e.Y.ToString();
25             if (Flag == 0)
26                 return;
27             Pen pen = new Pen(Color.Gray, 1);//灰色画笔,宽度为1
28             pen.DashStyle = DashStyle.Custom;
29             pen.DashPattern = new float[] { 9f, 1f };//虚线:实体和空白的比例
30             pen.StartCap = LineCap.RoundAnchor;//圆点开始
31             pen.EndCap = LineCap.ArrowAnchor;//结束为箭头
32             Graphics g = CreateGraphics();
33             //指定画图的呈现质量
34             g.SmoothingMode = SmoothingMode.HighQuality;
35             g.InterpolationMode = InterpolationMode.HighQualityBicubic;
36             g.CompositingQuality = CompositingQuality.HighQuality;
37             PointEnd.X = e.X;
38             PointEnd.Y = e.Y;
39             g.Clear(BackColor);//清除之前的画线
40             g.DrawLine(pen, PointStart.X, PointStart.Y, PointEnd.X, PointEnd.Y);//画线
41         }
42 
43         private void Form1_MouseDown(object sender, MouseEventArgs e)
44         {
45             Flag = 1;
46             PointStart.X = e.X;
47             PointStart.Y = e.Y;
48         }
49     }
50 }

 

posted @ 2021-03-02 14:49  新*  阅读(4646)  评论(0编辑  收藏  举报