1

Hi i tryied to move line object in my app.

Xaml:

<Canvas x:Name="canvas" Height="300" Width="350" MouseDown="Canvas_MouseDown" MouseMove="Canvas_MouseMove" MouseUp="Canvas_MouseUp" Background="Transparent" />

Code Behind:

private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
  startPoint = e.GetPosition(canvas);

  if (e.OriginalSource is Line)
        {
            linia = (Line)e.OriginalSource;
            if(!LineFocus)
                LineFocus = true;
            return;
        }
   else
     LineFocus = false;
}
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
  var pos = e.GetPosition(canvas);
  TranslateTransform ruch = new TranslateTransform(pos.X - startPoint.X, pos.Y - startPoint.Y);
  linia.RenderTransform = ruch;
}

It works fine my line is moved, but when I try to move it again it is moving from oryginal place (the place when i draw them at the very first time). When I checked it by MessageBox() with this:

...
linia = (Line)e.OriginalSource;
MessageBox.Show(linia.X1 + linia.Y1 + linia.X2 + linia.Y2);
...

Allways return exactly the same values even after move, so what is the reason of that?

4

1 回答 1

3

这些是我的编辑:

首先你需要两个点:一个起点(startPoint)和一个终点(pos)。在移动处理程序中,您将 newPoint 设置为相对于画布的当前鼠标位置。然后你取新点和旧点之间的差,你得到两个变量:dX 和 dY。现在您将这些差异添加到线的 Points 中,最后使新点指向下一个起点:

pos = e.GetPosition(canvas);
double dX = pos.X - startPoint.X;
double dy = pos.Y - startPoint.Y;
//if you want, you can put here an if- statement to check if the mouse is down
linia.X1 += dX;
linia.X2 += dX;
linia.Y1 += dY;
linia.Y2 += dY;
//Here comes the end of the if
startPoint = pos;

希望这对您有所帮助!

假设您想通过 2 个步骤更改位置:

线是这样的:

X1 = 70

X2 = 80

Y1 = 70

Y2 = 80

您将鼠标移动 x=1 和 y=1

位置 = (71, 81)

起点 = (70, 80)

1.步骤:

X1 = 70 + 71 - 70 = 71 与其他值相同

这条线是这样的:

X1 = 71

X2 = 81

Y1 = 71

Y2 = 81

现在将 startPoint 的值设置为 pos 的值:

起点 = (71, 81)

2.步骤

startPoint = (71, 81) pos = (72, 82) //你移动鼠标 1 和 1

这将得到这样的一行:

X1 = 71 + 72 - 71 = 72

X2 = 71 + 72 - 71 = 72

Y1 = 81 + 82 - 81 = 82

Y2 = 81 + 82 - 81 = 82

等等...

于 2013-04-25T11:20:32.273 回答