使用c#在两条线之间绘制链接或路径

Drawing a linkage or a path between two lines using c#

我正在尝试在两条线之间画一条路径,如下所示。

我使用了以下代码来做到这一点

        Pen usedpen= new Pen(Color.Black, 2);
        //Point[] p = {
        //    new Point(518,10),
        //    new Point(518,20),
        //    new Point(518-85,15)
        //};
        GraphicsPath path = new GraphicsPath();

        path.StartFigure();
        path.AddLine(new Point(518, 10), new Point(433, 10));
        path.AddLine(new Point(518, 40), new Point(433, 40));
        path.AddLine(new Point(433,10), new Point(433,40));
        //usedpen.LineJoin = LineJoin.Round;
        e.Graphics.DrawPath(usedpen, path);

但是使用这段代码后绘制了如下图形:

任何帮助
提前致谢

哦,你正在使用 onPaint 事件,所以问题是你正在绘制一条路径,这意味着点将从第一行的末尾到下一行的开头。

第一行之后

path.AddLine(new Point(518, 10), new Point(433, 10));

现在点在 (433, 10)

现在下一行说从 (518, 40) 到 (433, 40)

现在实际发生的是从 (433, 10) 到 (518, 40) 绘制了一条线,因为它是一条继续绘制的路径。

 GraphicsPath path = new GraphicsPath();
 path.StartFigure();
 path.AddLine(new Point(518, 10), new Point(433, 10));
 path.AddLine(new Point(433, 10), new Point(433, 40));
 path.AddLine(new Point(433, 40), new Point(518, 40));
 usedpen.LineJoin = LineJoin.Round;

默认情况下,每当您添加一个图形时,向 GraphicPath 说一条线,它的起点将连接到最后一个图形的终点。因此顺序很重要!

防止这种情况的方法是在你想绘制未连接行时使用StartFigure

Starts a new figure without closing the current figure. All subsequent points added to the path are added to this new figure.

    Pen usedpen= new Pen(Color.Black, 2);
    //Point[] p = {
    //    new Point(518,10),
    //    new Point(518,20),
    //    new Point(518-85,15)
    //};
    GraphicsPath path = new GraphicsPath();

    path.StartFigure();
    path.AddLine(new Point(518, 10), new Point(433, 10));
    path.StartFigure();   // <---
    path.AddLine(new Point(518, 40), new Point(433, 40));
    path.StartFigure();   // <---
    path.AddLine(new Point(433,10), new Point(433,40));
    //usedpen.LineJoin = LineJoin.Round;
    e.Graphics.DrawPath(usedpen, path);

当然你的问题基本上是错误的顺序或画线,所以其他答案是正确的。

顺便说一句,推荐的绘制连接线的方法是使用AddLines,因为它可以避免在线接头、端帽或斜接处出现问题..

类似的方法,使用GraphicsPath.AddLines()(也处理创建的对象)。

GraphicsPath.StartFigure() 未使用,因为它是唯一绘制的图形。当更多点添加到 GraphicsPath 时,.StartFigure() 将创建一个新的子路径,而不链接先前存在的子路径。

可以使用 GraphicsPathIterator.

解析子路径,以测试它们包含的形状类型
using (GraphicsPath path = new GraphicsPath())
{
    Point[] points = new Point[] {
        new Point(518, 10), new Point(433, 10),
        new Point(433, 40), new Point(433, 40),
        new Point(433, 40), new Point(518, 40)
    };

    path.AddLines(points);
    e.Graphics.DrawPath(new Pen(Color.Black, 2), path);

    //Add a new figure
    path.StartFigure();
    path.AddEllipse(new Rectangle(450, 40, 50, 50));
    e.Graphics.DrawPath(new Pen(Color.Black, 2), path);
};