在Windows应用商店应用中的画布上移动图像

时间:2015-04-09 08:41:41

标签: c# xaml canvas windows-store-apps

我需要在画布上移动图像并点按并滑动。我怎样才能做到这一点。我尝试了以下内容。图像正在移动,但不会在用户移动时移动。

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();
    }
}

1 个答案:

答案 0 :(得分:1)

您应该直接在画布中设置绝对位置,而不是使用TranslateTransform,因此您必须将ManipulationDelta事件绑定到Canvas,并检测影响点是否在图像。

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

这是新的事件处理功能:

   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);
        }
   }

简单如馅饼。您可以删除initialPtimg_ManipulationStarted