将Xamarin(Android)触摸事件坐标映射到网络视图像素



我在android xamarin应用程序中有一个网络视图。当用户向左或向右滑动屏幕时,我需要检查滑动是否发生在特定元素上。为了处理滑动逻辑,我使用了以下代码:

float startY = 0;
private void BindTouchEvents() {
float startX = 0;
float webViewWidth = 0;
webView.Touch += (sender, e) => {
if (e.Event.Action == Android.Views.MotionEventActions.Down)
{
webViewWidth = webView.Width;
startX = e.Event.GetX();
startY = e.Event.RawY; //I've tried both GetY and RawY here
}
if (e.Event.Action == Android.Views.MotionEventActions.Up)
{
float movement = e.Event.GetX() - startX;
float offset = webViewWidth / 2;
if (Math.Abs(movement) > offset)
{
if (movement < 0)
{
client.NotifyTouch(webView, e.Event.GetX(), startY, "SwipeLeft");
}
else
{
client.NotifyTouch(webView, e.Event.GetX(), startY, "SwipeRight");
}
}
}
e.Handled = false;
};
}

客户。NotifyTouch调用会调用网络视图中的一些javascript,以确定滑动事件是否发生在特定元素上。如果是,则会将该图元的可见性切换为隐藏。元素位于0,0的固定位置,高度为64px,因此此逻辑非常简单:

$scope.$on('received-touch-event', function (e, args) {     
if ($scope.showLaunchNavBar && (args.event === "SwipeLeft" || args.event === "SwipeRight") && args.y > 0 && args.y < 64) {
$scope.showLaunchNav(false);
};          
});

问题是startY值似乎不能均匀地转换为webview像素。例如,如果我尝试大致在0,0处滑动,并检查起始Y位置,它高于100,如果我试图大致在0,64处滑动,起始Y位置最终高于400。我需要弄清楚如何将这些值转换为WebView像素。我假设这与我的设备上的像素密度有关,但我不确定如何以一种通用的方式将值转换为"网络像素",这种方式适用于所有设备。

我试过在谷歌上搜索、阅读文档并在这里搜索答案,但似乎找不到我要找的东西。可能没有使用正确的术语。感谢您的帮助。

我相信我已经明白了,下面是解决方案:

public static float ConvertDpToPixel(float dp, Context context)
{
return dp / ((float)context.Resources.DisplayMetrics.DensityDpi / (float)DisplayMetricsDensity.Default);
}

最新更新