Xamarin.Forms菜鸟笔记--10.获取点击/滑动 Image位置
当点击一个Image标签的图片时,获取点击此图片的坐标位置
在Form中创建继承自Image的类
public class CustomImage : Image
{/// <summary>/// 点击/// </summary>public event Action<double, double> OnTapped;/// <summary>/// 滑动/// </summary>public event Action<double, double, double, double> OnSlide;/// <summary>/// /// </summary>/// <param name="x"></param>/// <param name="y"></param>public void RaiseTapped(double x, double y){OnTapped?.Invoke(x, y); // 触发点击位置事件}/// <summary>/// /// </summary>/// <param name="dx"></param>/// <param name="dy"></param>/// <param name="ux"></param>/// <param name="uy"></param>public void RaiseSlide(double dx, double dy, double ux, double uy){OnSlide?.Invoke(dx, dy,ux,uy); // 触发滑动事件}
}
在xaml中使用
xmlns:c="clr-namespace:abc.Controls"
<c:CustomImage Source="" x:Name="BackImg" HorizontalOptions="Start" VerticalOptions="FillAndExpand" OnTapped="HandleImageTapped" OnSlide="HandleImageSlide" />
在安卓中实现
[assembly: ExportRenderer(typeof(CustomImage), typeof(CustomImageRender))]
namespace abc.Droid.Render
{public class CustomImageRender : ImageRenderer{public CustomImageRender(Context context) : base(context) { }protected override void OnElementChanged(ElementChangedEventArgs<Image> e){base.OnElementChanged(e);if (e.NewElement != null){this.Touch += OnTouch;this.Touch += OnSlide;}if (e.OldElement != null){this.Touch -= OnTouch;this.Touch += OnSlide;}}private void OnTouch(object sender, TouchEventArgs e){if (e.Event.Action == MotionEventActions.Up){var x = e.Event.GetX();var y = e.Event.GetY();var customImage = (CustomImage)Element;customImage?.RaiseTapped(x, y);}}private void OnSlide(object sender, TouchEventArgs e){if (e.Event.Action == MotionEventActions.Up){var x = e.Event.GetX();var y = e.Event.GetY();var customImage = (CustomImage)Element;customImage?.RaiseSlide(0,0,x, y);}else if (e.Event.Action == MotionEventActions.Down){var x = e.Event.GetX();var y = e.Event.GetY();var customImage = (CustomImage)Element;customImage?.RaiseSlide( x, y, 0, 0);}}}
}
