【问题标题】:C# move a PolylineC# 移动折线
【发布时间】:2018-08-05 07:58:38
【问题描述】:

我是 C# 图形编程的新手。昨天我开始了一个新项目(WPF)。有一个折线对象,我必须使用我正在计算的坐标沿着屏幕移动。我不知道如何移动对象并制作类似动画的东西。在鼠标按下时,我想启动这个方法Move(),然后进入while循环,当条件完成时(end == true)我想结束循环并完成动画。当我在循环中时,我的想法是缓慢移动我的折线。我试图将Move() 放入一个线程并使用Thread.Sleep(...);,但我只能看到结束位置,而不是折线的全部位置。 我试着把它放入new Thread(new ThreadStart(Move)); ...和this.Dispatcher.BeginInvoke,效果是一样的。 请告诉我,我怎样才能做出这个动作?

     public void Move()
     {
        bool end = false;
        while (!end)
        {
            double x = lastPosX;
            double y = lastPosY;

            double a = y1 - y;
            double b = x - x1;
            double c = -x * y1 + x1 * y;

            double u, v;
            GetC(out u, out v);                    

            if (y1 < lastPosY)
            {
                GetCoordinates(ref u, ref v);
            }

            if (u > width || v > height)
            {
                 gameEnd = true;
            }

            lastPosX = u;
            lastPosY = v;

            p.Points.Remove(p.Points.First());
            p.Points.Add(new Point(u, v));

          }

       }

【问题讨论】:

  • 您的代码令人困惑。如何将“end”设置为 true 以退出循环?此外,您使用了许多我们不知道的变量。

标签: c# wpf multithreading animation


【解决方案1】:

我不太明白您的 Move 方法是如何工作的,但这里有一个示例,说明如何在 MouseDown 时将折线从左移动到右。希望您能够根据自己的需要进行调整

Xaml

<Canvas Name="myCanvas">
    <Polyline Name="myPolyline"
              MouseDown="Polyline_MouseDown"
              Canvas.Left="75"
              Canvas.Top="50"
              Points="25,25 0,50 25,75 50,50 25,25 25,0" 
              Stroke="Blue"
              StrokeThickness="10"/>
</Canvas>

背后的代码

private void Polyline_MouseDown(object sender, MouseButtonEventArgs e)
{
    double left = Canvas.GetLeft(myPolyline);
    var animationThread = new Thread(new ThreadStart(() =>
    {
        while (left < 300)
        {
            left += 10;
            // SetLeft is done in the UI thread
            Dispatcher.Invoke(new Action(() =>
            {
                Canvas.SetLeft(myPolyline, left);
            }));
            Thread.Sleep(50);
        }
    }));
    animationThread.Start();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2021-12-28
    相关资源
    最近更新 更多