我有下面的代码,它允许我在两个给定点之间画一条线。我需要做的是将这些线都以两种方式延伸,以使线以相同角度延伸到线的两端
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);
}
答案 0 :(得分:0)
尝试使用该方法:
startPoint和endPoint是著名点。 p1和p2是新的起点和终点。
public static void FindSimmetricPointsOnLine(Point startPoint, Point endPoint, double distance, out Point p1, out Point p2)
{
p1 = new Point();
p2 = new Point();
var xa = startPoint.X;
var ya = startPoint.Y;
var xb = endPoint.X;
var yb = endPoint.Y;
var l = distance;
double x1 = 0;
double x2 = 0;
double y1 = 0;
double y2 = 0;
if (xa == xb)
{
x1 = x2 = xa;
y1 = ya + l;
y2 = ya - l;
}
else
{
if (ya == yb)
{
y1 = y2 = ya;
x1 = xa + l;
x2 = xa - l;
}
else
{
var K = (ya - yb)/(xa - xb);
var B = ya - K*xa;
var A1 = K*K + 1;
var B1 = -2*(xa + K*(ya - B));
var C1 = xa*xa + (ya - B)*(ya - B) - l*l;
var D = B1*B1 - 4*A1*C1;
if (D >= 0)
{
x1 = (-B1 + Math.Sqrt(D))/(2*A1);
x2 = (-B1 - Math.Sqrt(D))/(2*A1);
y1 = K*x1 + B;
y2 = K*x2 + B;
p1 = new Point(x1, y1);
p2 = new Point(x2, y2);
}
}
}
}
答案 1 :(得分:-1)
这里有一些代码可以满足您的需求。
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;