如何从 WPF PolyLine 对象移动所有坐标?

Pat*_*ins 4 .net c# wpf polyline

我有一个用折线对象动态制作的图形。它产生了一些有趣的东西,但我只想保留最后 10 个坐标,一旦我们到达第 10 个位置,每个坐标都会向左移动 X 像素,新值将在最后添加。

在我的绘图类的 Add 函数中,我尝试了这种代码:

        if (points.Count > 10)
        {
            myPolyline.Points.RemoveAt(0);

            foreach(Point p in myPolyline.Points)
            {
                p.X = p.X - 50;//Move all coord back to have a place for the new one
            }   
        }
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为我们无法在 ForEach 循环中修改集合的变量。在 WPF/C# 中执行此操作的最佳方法是什么?

更多信息

我可以这样做:

            for (int i = 0; i < this.myPolyline.Points.Count; i++)
            {
                this.myPolyline.Points[i] = new Point(this.myPolyline.Points[i].X - 50, this.myPolyline.Points[i].Y);
            }
Run Code Online (Sandbox Code Playgroud)

但我想要一种更简洁的方法来做到这一点,而不必非常时间创建点对象。

Joe*_*ant 5

嗯,这Point是一个结构,所以创建新的开销应该不错。执行以下...

Point p = this.myPolyline.Points[i];
p.X -= 50;
this.myPolyline.Points[i] = p;
Run Code Online (Sandbox Code Playgroud)

...真的没有什么不同,仅仅因为结构是按值传递的。

考虑到以下情况,您几乎陷入for循环并重新分配给myPolyline.Points[i]

  1. 您必须Point使用不同的X值修改。
  2. 你不能修改foreach循环的变量,所以你必须使用for循环。
  3. myPolyline.Points[i].X -= 50由于Point从数组中检索结构然后不自动重新分配的方式,将无法工作。

如果您只是想移动整个PolyLine,我可能会建议使用LayoutTransformRenderTransform,但是您要移动Points 的一个子集,然后再添加其他。

编辑:如果你真的想重构那个操作,你可以PointCollectionfor循环创建一个扩展方法并像这样调整点:

static public void ChangePoints( this PointCollection pc, Vector v ) {
    for (int i = 0; i < pc.Count; i++ ) {
        pc[i] += v;
        // the above works on the indexer because you're doing an operation on the
        // Point rather than on one of the Point's members.
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

myPolyline.Points.ChangePoints( new Vector( -50, 0 ) );
Run Code Online (Sandbox Code Playgroud)

您仍然必须以Point相同的方式更改s,但它已在其他地方进行了重构,以使用法更具可读性。并且使用Vector也使其更具可读性。