You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI中如何获取PanGestureRecognizer的绝对位置?

解决GraphicsView中Pan手势获取绝对位置的问题

要获取Pan手势的绝对位置,由于PanUpdatedEventArgs仅提供相对变化量(TotalX/TotalY),需要自行维护手势开始时的初始绝对位置,结合变化量计算当前绝对位置。具体实现步骤如下:

1. 修改XAML,添加PointerPressed事件

给GraphicsView添加触摸开始事件,用于记录手势初始位置:

<GraphicsView x:Name="Canvas" Drawable="{StaticResource Renderer}"
              PointerPressed="Canvas_PointerPressed">
    <GraphicsView.GestureRecognizers>
        <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
        <PanGestureRecognizer PanUpdated="PanGestureRecognizer_PanUpdated" />
    </GraphicsView.GestureRecognizers>
</GraphicsView>

2. 声明变量存储初始位置

在代码后台添加私有字段,保存Pan手势开始时的绝对坐标:

private Point _panStartAbsolutePosition;

3. 实现PointerPressed事件,记录初始绝对位置

通过PointerEventArgs的GetPosition方法获取触摸开始时的绝对位置:

private void Canvas_PointerPressed(object sender, PointerEventArgs e)
{
    // 获取相对于当前GraphicsView的绝对位置,若需屏幕绝对位置,参数传null
    _panStartAbsolutePosition = e.GetPosition(Canvas);
}

4. 在PanUpdated事件中计算当前绝对位置

结合初始位置与TotalX/TotalY的变化量,得到当前绝对坐标:

private void PanGestureRecognizer_PanUpdated(object sender, PanUpdatedEventArgs e)
{
    switch (e.StatusType)
    {
        case GestureStatus.Running:
            // 计算当前绝对位置:初始位置 + 手势总变化量
            double currentAbsoluteX = _panStartAbsolutePosition.X + e.TotalX;
            double currentAbsoluteY = _panStartAbsolutePosition.Y + e.TotalY;
            Debug.WriteLine($"当前绝对位置 X: {currentAbsoluteX}, Y: {currentAbsoluteY}");
            break;
        case GestureStatus.Completed:
            // 手势结束后的收尾处理(可选)
            break;
    }
}

注意事项

  • PointerPressed事件会与Pan手势的Started状态同步触发,确保初始位置记录的准确性。
  • GetPosition的参数可按需调整:传入Canvas则获取相对于控件的位置,传入null则获取相对于屏幕的绝对位置。

内容的提问来源于stack exchange,提问作者Junta Tanki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 20:38:26