1

我正在尝试根据这样的点击/单击设置图像的位置(注意“contentGrid”是 Page 的唯一子级并填充屏幕)

 private void contentGrid_Tapped(object sender, TappedRoutedEventArgs e)
 {
     Uri uri = new Uri("ms-appx:///Images/Test.png");
     BitmapImage bitmap = new BitmapImage(uri);
     Image image = new Image();
     image.Source = bitmap;

     // The .png is a 30px by 30px image
     image.Width = 30;
     image.Height = 30;
     image.Stretch = Stretch.None;

     Point tappedPoint = e.GetPosition(contentGrid);
     TranslateTransform posTransform = new TranslateTransform();
     posTransform.X = tappedPoint.X;
     posTransform.Y = tappedPoint.Y;
     image.RenderTransform = posTransform;
     contentGrid.Children.Add(image);         
 }

结果是 Test.png 的图像在单击时出现在页面上,但不在我点击/单击的位置。它在视觉上偏移了页面宽度的一半,并向下偏移了页面高度的一半。

我试图在这里了解相对位置 - 将图像转换为用户实际点击/单击的点的最佳方法是什么?

4

2 回答 2

3

尝试将Margin图像设置为显示到鼠标点:

   private void contentGrid_Tapped(object sender, TappedRoutedEventArgs e)
   {
        Uri uri = new Uri("ms-appx:///Images/Test.png");
        BitmapImage bitmap = new BitmapImage(uri);
        Image image = new Image();
        image.Source = bitmap;


        // The .png is a 30px by 30px image
        image.Width = 30;
        image.Height = 30;
        image.Stretch = Stretch.None;

        image.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
        image.VerticalAlignment = System.Windows.VerticalAlignment.Top;
        Point tappedPoint = e.GetPosition(contentGrid);
        contentGrid.Children.Add(image);
        image.Margin = new Thickness(tappedPoint.X, tappedPoint.Y, 0, 0);
    }
于 2012-12-02T23:11:59.533 回答
3

Grid在您的情况下使用它很棘手。使用画布代替Grid.

Canvas.SetLeft(image, tappedPoint.X);
Canvas.SetTop(image, tappedPoint.Y);
canvas.Children.Add(image);
于 2012-12-05T15:45:08.387 回答