首页 > 解决方案 > 在两点之间画线并在两侧延长线

问题描述

我有下面的代码,它允许我在两个给定点之间画一条线。我需要做的是双向延伸这些线,使线以相同的角度延伸到线的两侧

private void Form1_Load(object sender, EventArgs e)
{
    this.Controls.Add(new Panel{Left = 10, Top = 10,Width = 50,Height = 50, BackColor = Color.Blue});
    this.Controls.Add(new Panel {Left = 100, Top = 100,Width = 50,Height = 50, BackColor = Color.Blue});


}
protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    Graphics g;
    g = e.Graphics;
    Pen myPen = new Pen(Color.Red);
    myPen.Width = 1;
    g.DrawLine(myPen, 12, 12, 45, 65);
    g.DrawLine(myPen, 100, 100, 45, 65);
}

标签: c#winforms

解决方案


这是一些应该做你需要的代码。

public void ExtendLine(Point p1, Point p2, double distance, out Point start, out Point end)
{
    //first find the vector that represents the direction of the line
    Vector direction = p2 - p1;

    //normalize the vector to a distance of one point
    direction.Normalize();

    //multiply the direction by to total distance to find the offset amount
    Vector offset = (direction * distance);

    //subtract the offset from the start point to find the new start point
    start = p1 - offset;

    //add the offset to the end point to find the new end point
    end = p2 + offset;
}

这是一个显示如何使用该方法的示例。

Point p1 = new Point(Line1.X1, Line1.Y1), p2 = new Point(Line1.X2, Line1.Y2);
ExtendLine(p1, p2, 10, out Point p3, out Point p4);
Line2.X1 = p3.X;
Line2.Y1 = p3.Y;
Line2.X2 = p4.X;
Line2.Y2 = p4.Y;

推荐阅读