Xamarin.Forms Place a pin where the user touched the screen with MR.Gestures


Xamarins built in gesture recognizers provide only very basic touch handling. E.g. there is no way to get the position of a touching finger. MR.Gestures is a component which adds 14 different touch handling events. The position of the touching fingers is part of the EventArgs passed to all MR.Gestures events.

If you want to place a pin anywhere on the screen, the easiest way is to use an MR.Gestures.AbsoluteLayout which handles the Tapping event.

<mr:AbsoluteLayout x:Name="MainLayout" Tapping="OnTapping">

As you can see the Tapping="OnTapping" also feels more like .NET than Xamarins syntax with the nested GestureRecognizers. That syntax was copied from iOS and it smells a bit for .NET developers.

In your code behind you could add the OnTapping handler like this:

private void OnTapping(object sender, MR.Gestures.TapEventArgs e)
    if (e.Touches?.Length > 0)
        Point touch = e.Touches[0];
        var image = new Image() { Source = "pin" };
        MainLayout.Children.Add(image, touch);

Instead of the Tapping event, you could also use the TappingCommand and bind to your ViewModel, but that would complicate things in this simple example.

More samples for MR.Gestures can be found in the GestureSample app on GitHub and on the MR.Gestures website. These also show how to use all the other touch events with event handlers, commands, MVVM, ...