在C#中的Picturebox上绘制一个箭头

我希望能够从一个鼠标点击位置绘制一个直箭头,就像你在PowerPoint中一样。 它也需要能够在PictureBox上绘图。

下面是一些基本代码,用于在图片框中从鼠标到当前位置绘制线条。
你只需要为箭头绘制更多的线条或三角形。

public partial class Form1 : Form { private bool isMoving = false; private Point mouseDownPosition = Point.Empty; private Point mouseMovePosition = Point.Empty; private List> lines = new List>(); public Form1() { InitializeComponent(); // // pictureBox1 // this.pictureBox1.Location = new System.Drawing.Point(0, 0); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(231, 235); this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; this.pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint); this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown); this.pictureBox1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseMove); this.pictureBox1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseUp); this.Controls.Add(this.pictureBox1); } private void pictureBox1_Paint(object sender, PaintEventArgs e) { var g = e.Graphics; if (isMoving) { g.Clear(pictureBox1.BackColor); g.DrawLine(Pens.Black, mouseDownPosition, mouseMovePosition); foreach (var line in lines) { g.DrawLine(Pens.Black, line.Item1, line.Item2); } } } private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { isMoving = true; mouseDownPosition = e.Location; } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (isMoving) { mouseMovePosition = e.Location; pictureBox1.Invalidate(); } } private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { if (isMoving) { lines.Add(Tuple.Create(mouseDownPosition, mouseMovePosition)); } isMoving = false; } } 

绘制箭头很容易,就像你在前一个问题中找出如何在PictureBox上绘制线条一样。

您所要做的就是为已用于绘制线条的Pen对象指定StartCapEndCap 。 直观地说, StartCap属性允许您指定在使用Pen对象绘制的任何行的开头使用的上限样式,而EndCap属性允许您为行的末尾指定上限样式。

有几种不同的LineCap样式可供选择,包括:

  Flat指定扁平线帽。
 方形指定方形线帽。
 圆形指定圆形线帽。
 三角形指定三角形线帽。
 NoAnchor指定无锚点。
 SquareAnchor指定方形锚线帽。
 RoundAnchor指定圆形锚帽。
 DiamondAnchor指定钻石锚帽。
 ArrowAnchor指定箭头形状的锚帽。
 自定义指定自定义行上限。
 AnchorMask指定用于检查线帽是否为锚帽的掩码。

在这种情况下,您可能会发现ArrowAnchor样式最有用: 只需将ArrowAnchor指定为行的开头或结尾的LineCap样式(取决于您希望箭头指向的方向)。

以下代码将绘制一条绿色,右向箭头,线条粗细为4:

 private void pictureBox1_Paint(object sender, PaintEventArgs e) { //Create a new pen to draw the arrow with using (Pen p = new Pen(Brushes.Green, 4f)) { //Specify the EndCap, because we're drawing a right-facing arrow p.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor; //Draw the arrow e.Graphics.DrawLine(p, 0, 0, 30, 45); } } 

参考Albin Sunnanbo的答案,这是很棒的东西

如果你想画箭头只需更换

  g.DrawLine(Pens.Black, mouseDownPosition, mouseMovePosition); 

 Pen p = new Pen(Color.Black,3); p.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor; g.DrawLine(p, mouseDownPosition, mouseMovePosition); p.Dispose();