c# - 在两点之间画线并在两侧延长线
问题描述
我有下面的代码,它允许我在两个给定点之间画一条线。我需要做的是双向延伸这些线,使线以相同的角度延伸到线的两侧
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);
}
解决方案
这是一些应该做你需要的代码。
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;
推荐阅读
- javascript - How do I make a React prop only required when used in the context of a Container component with Typescript?
- mysql - 在 Connection.query (/var/www/html/node_modules/mysql/lib/Connection.js:198:25)
- javascript - 不和谐.js | UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“部分”
- django - 视图 ecommerceapp.views.CheckoutView 没有返回 HttpResponse 对象。它返回 None 而不是
- r - 如何修复这个 if_else 语句
- android - 使用两个按钮启动、停止和重新启动 TimerTask
- pandas - Pandas 将列值转换为列
- next.js - 如何在不使用 +150k 静态页面重建应用的情况下添加新页面?
- jquery - 使用 seiyria 的 bootstrap-slider 根据输入值调整范围
- c - C 语言中的 open() 是跨平台的吗?