Search code examples
xamarin.formstouch

How to trigger touch start (not when the finger released) in the xamarin forms?


The problem is that TapGestureRecognizer triggers only when I release my finger, but I want to trigger when I just started the touch

Here is the way how I use it at the moment:

<Image.GestureRecognizers>
    <TapGestureRecognizer
         Tapped="TapGestureRecognizer_Tapped"
         NumberOfTapsRequired="1" />
</Image.GestureRecognizers>

Solution

  • You can try to use a custom render to do something you want when the user touches the image.

    1. Declare the custom image in the share project:

      public class MyImage : Image
      {
      }
      
    2. In the android part:

      [assembly: ExportRenderer(typeof(MyImage), typeof(MyImageRenderer))]
      namespace AppTest.Droid
      {
      
          public class MyImageRenderer : ImageRenderer
          {
              public MyImageRenderer(Context context) : base(context) { }
              public override bool OnTouchEvent(MotionEvent e)
              {
                  if(e.Action == MotionEventActions.Down)
                  {
                      //do something
                  }
      
                  return base.OnTouchEvent(e);
      
              }
          }
      }
      
    3. In the ios part:

      [assembly: ExportRenderer(typeof(MyImage), typeof(MyImageRenderer))]
      namespace AppTest.iOS
      {
          public class MyImageRenderer : ImageRenderer
          {
              protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
              {
                  base.OnElementChanged(e);
                  if (Control != null)
                  {
                      Control.UserInteractionEnabled = true;
                  }
              }
              public override void TouchesBegan(NSSet touches, UIEvent evt)
              {
                  //do something
                  base.TouchesBegan(touches, evt);
              }
      
          }
      }
      
    4. Use it in the xaml:

      <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
           xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
           xmlns:local="clr-namespace:AppTest"
           x:Class="AppTest.MainPage">
          <StackLayout>
            <local:MyImage Source="your image" BackgroundColor="Blue"/>
          </StackLayout>
      
      </ContentPage>