TranslateTransform Not translating lines

226 views Asked by At

I've been trying to translate a grid (2 arrays of lines) in a canvas via TranslateTransform. However, the lines kind of just shake about and return to their original place and do not translate. Here's the source:

    private Point mousePosition;
    private bool CanvasMouseDown;

    private void GraphMouseDown(object sender, MouseButtonEventArgs e)
    {
        CanvasMouseDown = true;
    }

    private void GraphMouseMove(object sender, MouseEventArgs e)
    {
        if (CanvasMouseDown)
        {
            var position = e.GetPosition(canvas);
            var offset = position - mousePosition;
            mousePosition = position;

            for (int i = 0; i < GridLinesHoriz.Length; ++i)
            {
                GridLinesHoriz[i].RenderTransform = new TranslateTransform(offset.X, offset.Y);
            }

            for (int i = 0; i < GridLinesVert.Length; ++i)
            {
                GridLinesVert[i].RenderTransform = new TranslateTransform(offset.X, offset.Y);
            }
        }
    }


    private void GraphMouseUp(object sender, MouseButtonEventArgs e)
    {
        CanvasMouseDown = false;
    }

Any Help?

1

There are 1 answers

0
Jason Tyler On BEST ANSWER

The problem is you are normalizing the offset as you are handling the MouseMove events. The TranslateTransform always translates from the original location, so you need to compute a running offset that's maintained for the lifetime of the drag operation.

If you changemousePosition to class level variable and set that variable when the operation starts (in the MouseDown event handler) and stop updating that variable in the MouseMove event handler, the lines will start translating the way you expect.

point mousePosition;

private void GraphMouseDown(object sender, MouseButtonEventArgs e)
{
    CanvasMouseDown = true;
    mousePosition  = e.GetPosition(canvas);
}

private void GraphMouseMove(object sender, MouseEventArgs e)
{
    if (CanvasMouseDown)
    {
        var position = e.GetPosition(canvas);
        var offset = position - mousePosition;

        for (int i = 0; i < GridLinesHoriz.Length; ++i)
        {
            GridLinesHoriz[i].RenderTransform = new TranslateTransform(offset.X, offset.Y);
        }

        for (int i = 0; i < GridLinesVert.Length; ++i)
        {
            GridLinesVert[i].RenderTransform = new TranslateTransform(offset.X, offset.Y);
        }
    }
}