如何在xamarin形式中触发触摸启动(而不是当手指释放时)



问题是TapGestureRecognizer只在我松开手指时触发,但我想在刚启动触摸时触发

以下是我目前使用它的方式:

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

当用户触摸图像时,可以尝试使用自定义渲染来执行您想要的操作。

  1. 在共享项目中声明自定义图像:

    public class MyImage : Image
    {
    }
    
  2. 在android部分:

    [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. 在ios部分:

    [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. 在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>
    

最新更新