我正在用wpf创建一个程序来绘制折线以及一条平行的偏移线。它适用于第一组平行线,但在每一行后面,右线偏离角度(以红色显示)。
到目前为止
代码:
private void DrawingCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) {
if (polylineLeft != null) {
var canvas = (Canvas)sender;
leftSegment.Points[1] = e.GetPosition(canvas);
var distance = (leftSegment.Points[0] - leftSegment.Points[1]).Length;
if (distance >= 20) {
polylineLeft.Points.Add(leftSegment.Points[1]);
//calculate second line
var L = Math.Sqrt((leftSegment.Points[0].X - leftSegment.Points[1].X) *
(leftSegment.Points[0].X - leftSegment.Points[1].X) +
(leftSegment.Points[0].Y - leftSegment.Points[1].Y) *
(leftSegment.Points[0].Y - leftSegment.Points[1].Y));
var x1p = leftSegment.Points[0].X + width * (leftSegment.Points[1].Y-leftSegment.Points[0].Y) / L;
var x2p = leftSegment.Points[1].X + width * (leftSegment.Points[1].Y-leftSegment.Points[0].Y) / L;
var y1p = leftSegment.Points[0].Y + width * (leftSegment.Points[0].X-leftSegment.Points[1].X) / L;
var y2p = leftSegment.Points[1].Y + width * (leftSegment.Points[0].X-leftSegment.Points[1].X) / L;
if (!initialLeftPoint) {
polylineRight.Points.Clear();
polylineRight.Points.Add(new Point(x1p, y1p));
initialLeftPoint = true;
}
polylineRight.Points.Add(new Point(x2p, y2p));
leftSegment.Points[0] = leftSegment.Points[1];
rightSegment.Points[0] = rightSegment.Points[1];
} else {
if (polylineLeft.Points.Count < 2) {
canvas.Children.Remove(polylineLeft);
}
polylineLeft = null;
polylineRight = null;
leftSegment.Points.Clear();
rightSegment.Points.Clear();
canvas.Children.Remove(leftSegment);
canvas.Children.Remove(rightSegment);
}
}
}
如何确保在我的第二行(红色)它与主线(绿色)平行?
答案 0 :(得分:1)
在WPF Vector结构的帮助下,问题的一部分很容易解决。给定两个点p1
和p2
之间的线段,您可以像这样计算法线向量:
Point p1 = ...
Point p2 = ...
var v = p2 - p1;
var n = new Vector(v.Y, -v.X);
n.Normalize();
// now n is a Vector of length 1, perpendicular to the line p1-p2
您现在可以创建一个平行线段(由点p3
和p4
给出),如下所示:
var distance = 20d;
var p3 = p1 + n * distance;
var p4 = p3 + v;
但是,上面的代码创建了一个与原始行相同长度的平行线段。这可能不是你想要的,因为我想你想创建一个“平行折线”。如果是这种情况,事情会变得复杂一些,因为您还必须计算平行折线的相邻线段之间的交点。在这些计算中,甚至可能会发生其中一些片段消失。