【问题标题】:Draw polyline on PictureBox在 PictureBox 上绘制折线
【发布时间】:2011-11-13 12:43:13
【问题描述】:

我想在PictureBox 上绘制折线(一条由一条或多条线段组成的连续线)。

在此我们可以通过指定每条线段的端点来创建多条线,并计算每条线段的距离,即每条线的距离。

【问题讨论】:

  • 问得很好。图像是最好的。人们喜欢误解!

标签: c# winforms graphics polyline


【解决方案1】:

如果您想在图片框上执行此操作,最简单的方法是从PictureBox 继承您自己的控件,并提供当您将鼠标悬停在图片框上时添加端点的功能。

然后将鼠标单击的位置存储在列表中,并覆盖OnPaint 以绘制端点(我选择了一个 4x4 正方形)和每个端点之间的一条线。这是基本代码:

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 一样将其添加到 Form 中,然后选择您的图像以通常的方式进入其中。

如果您尝试在图片框内单击几次,您会看到它绘制的端点就像您的示例图像一样。这是我机器上的一个例子:

然后你的下一个要求,获取端点之间的距离。这可以通过添加一个类来表示 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;
}

【讨论】:

猜你喜欢
  • 2011-09-08
  • 1970-01-01
  • 2018-07-06
  • 2016-04-12
  • 2013-05-23
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多