我希望在PictureBox
上绘制折线(由一个或多个线段组成的连续线)。
我们可以通过指定每个线段的端点来创建多条线,并计算每个线段的距离即每条线的距离。
public class EndPointPictureBox : PictureBox
{
private List<PointF> points = new List<PointF>();
public EndPointPictureBox()
{
}
protected override void OnMouseDown(MouseEventArgs e)
{
points.Add(new PointF(e.X,e.Y));
base.OnMouseDown(e);
this.Invalidate();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
Graphics g = pe.Graphics;
foreach(var point in points)
g.DrawRectangle(Pens.Black,point.X-2.0f,point.Y-2.0f,4.0f,4.0f);
if(points.Count>1)
g.DrawLines(Pens.Black,points.ToArray());
}
}
现在,您可以像添加PictureBox一样将其添加到表单中,并按照通常的方式选择要放入其中的图像。
如果您尝试在PictureBox内点击几次,您会看到它绘制了您的端点,就像您的示例图像一样。以下是我机器上的一个示例:
接下来,您的要求是获取端点之间的距离。这可以通过添加一个表示EndPoint
的类并引用其相邻节点来完成。然后使用一些简单的勾股定理数学即可得到当前点和下一个点之间的距离:
public class EndPoint
{
public EndPoint(int index, List<PointF> points)
{
this.Position = points[index];
if (index < points.Count - 1)
this.Next = points[index + 1];
}
public PointF Position { get; private set; }
public PointF Next { get; private set; }
public double GetDistanceToNext()
{
if(this.Next == PointF.Empty)
return 0;
var xDiff = this.Position.X - Next.X;
var yDiff = this.Position.Y - Next.Y;
return Math.Abs(Math.Sqrt((xDiff*xDiff) + (yDiff*yDiff)));
}
}
而且您可以添加一个方法到您的新 PictureBox
中来获取这些列表:
public List<EndPoint> GetEndPoints()
{
var list = new List<EndPoint>();
for(var i=0;i<points.Count;i++)
list.Add(new EndPoint(i,points));
return list;
}