Search code examples
c#xamlcanvaswindows-store-apps

Move an image over a canvas in windows store app


I need to move an image over a canvas on tap and slide. How can I achieve this. I tried the following. The image is moving but not as the user moves it.

XAML

<Canvas Background="White">
     <Image Name="img" Width="200" Height="200" Source="Assets/11.png" ManipulationMode="All"  ManipulationStarted="img_ManipulationStarted" ManipulationDelta="img_ManipulationDelta"/>
</Canvas>

C#

private Point initialPt;
private void img_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
{
    initialPt = e.Position;
}

private void img_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
    Point currentPt = e.Position;
    double x = currentPt.X - initialPt.X;
    double y = currentPt.Y - initialPt.Y;
    if (x != 0 || y != 0)
    {
        TranslateTransform posTransform = new TranslateTransform();
        posTransform.X = currentPt.X;
        posTransform.Y = currentPt.Y;
        img.RenderTransform = posTransform;
        e.Complete();
    }
}

Solution

  • Instead of using a TranslateTransform, you should directly set the absolute position in the canvas, so you have to bind the ManipulationDelta event to the Canvas, and detect if the point of impact is inside of the image.

    <Canvas Background="White" ManipulationMode="All"  ManipulationDelta="canvas_ManipulationDelta">
         <Image Name="img" Width="200" Height="200" Source="Assets/11.png"/>
    </Canvas>
    

    Here is the new event handling function:

       private void canvas_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
       {
            if ((e.Position.X > Canvas.GetLeft(img) && e.Position.X < Canvas.GetLeft(img) + img.Width) 
               || (e.Position.Y > Canvas.GetTop(img) && e.Position.Y < Canvas.GetTop(img) + img.Height)) {        
            { 
                 Canvas.SetLeft(img, e.Position.X);
                 Canvas.SetTop(img, e.Position.Y);
            }
       }
    

    Simple as pie. You can remove initialPt and img_ManipulationStarted.