1

I am trying to set the position of an Image based on a tap / click like this (note "contentGrid" is the only child of Page and fills the screen)

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

The result is that the Image of Test.png appears on the page when clicked, but not at the position where I tap / click. It is offset visually by half the page width and down by half the page height.

I am trying to understand relative positions here - what's the best way to transform the Image to the point where the user actually tapped / clicked?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
MJR
  • 81
  • 2
  • 5

2 Answers2

3

Try setting the Margin of the image to display to the mouse points:

   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);
    }
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
sa_ddam213
  • 42,848
  • 7
  • 101
  • 110
3

It's tricky to use Grid in your case. Use Canvas instead of Grid.

Canvas.SetLeft(image, tappedPoint.X);
Canvas.SetTop(image, tappedPoint.Y);
canvas.Children.Add(image);
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Vladimir Dorokhov
  • 3,784
  • 2
  • 23
  • 26