VisualTreeHelper.HitTest 报告命中,即使矩形远离基础形状也是如此

VisualTreeHelper.HitTest reports a hit even when rectangle is nowhere near the underlying shapes

我正在尝试在 canvas 上实现 WPF 路径对象的橡皮筋选择。不幸的是,我对矩形几何形状的 VisualTreeHelper.HitTest 的使用并不像我预期的那样有效。

我希望只有当我的橡皮筋矩形的某些部分与直线的直线路径相交时才会被击中。但是对于矩形,只要我的矩形位于线的左侧或上方的任何位置,我都会受到打击,即使我离线甚至它的边界框都不远。

有什么方法可以解决这个问题或我做错了什么明显的事情吗?

我写了一个简单的应用程序来演示这个问题。这是一条线和一个标签。如果我对 VisualTreeHelper.HitTest 的调用(使用橡皮筋矩形)检测到它超出了形状,我将底部的标签设置为可见。否则标签是折叠的。

我在这里,正如我所料,它检测到命中。这个不错。

我在这里在线下,没有命中。这个也不错

但是只要我在线的左侧或上方的任何地方,无论多远,我都会受到打击

这是测试应用 window:

<Window x:Class="WpfApp1.MainWindow"


        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:po="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"
        Title="MainWindow" Height="500" Width="525">
    <Window.Resources>

        <LineGeometry x:Key="LineGeo" StartPoint="50, 100" EndPoint="200, 75"/>
    </Window.Resources>
    <Canvas 
        x:Name="MyCanvas"
        Background="Yellow"
        MouseLeftButtonDown="MyCanvas_OnMouseLeftButtonDown"
        MouseMove="MyCanvas_OnMouseMove"
        MouseLeftButtonUp="MyCanvas_OnMouseLeftButtonUp"
        >

        <!-- The line I hit-test -->

        <Path x:Name="MyLine" Data="{StaticResource LineGeo}" 
              Stroke="Black" StrokeThickness="5" Tag="1234" />

        <!-- This label's is hidden by default and only shows up when code-behind sets it to Visible -->

        <Label x:Name="MyLabel"  Canvas.Left="100"  Canvas.Top="200" 
               Content="HIT DETECTED!!!" FontSize="25"  FontWeight="Bold" 
               Visibility="{x:Static Visibility.Collapsed}"/>

    </Canvas>
</Window>

这里是带有 HitTest 代码的鼠标代码隐藏处理程序

using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow() => InitializeComponent();

        private Point _startPosition;
        Path _path;
        private RectangleGeometry _rectGeo;
        private static readonly SolidColorBrush _brush = new SolidColorBrush(Colors.BlueViolet) { Opacity=0.3 };


        private void MyCanvas_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
            MyCanvas.CaptureMouse();
            _startPosition = e.GetPosition(MyCanvas);

            // Create the visible selection rect and add it to the canvas

            _rectGeo = new RectangleGeometry();
            _rectGeo.Rect = new Rect(_startPosition, _startPosition);
            _path = new Path()
            {
                Data = _rectGeo, 
                Fill =_brush,
                StrokeThickness = 0,
                IsHitTestVisible = false
            };

            MyCanvas.Children.Add(_path);
        }

        private void MyCanvas_OnMouseMove(object sender, MouseEventArgs e)
        {
            // Sanity check

            if (e.MouseDevice.LeftButton != MouseButtonState.Pressed ||
                null == _path ||
                !MyCanvas.IsMouseCaptured)
            {
                return;
            }  

            e.Handled = true;

            // Get the second position for the rect geometry

            var curPos    = e.GetPosition(MyCanvas);
            var rect      = new Rect(_startPosition, curPos);
            _rectGeo.Rect = rect;
            _path.Data    = _rectGeo;

            // This is set up like a loop because my real production code is looking
            // for many shapes.

            var paths          = new List<Path>();
            var htp            = new GeometryHitTestParameters(_rectGeo);
            var resultCallback = new HitTestResultCallback(r => HitTestResultBehavior.Continue);
            var filterCallback = new HitTestFilterCallback(
                el =>
                {
                    // Filter accepts any object of type Path.  There should be just one

                    if (el is Path s && s.Tag != null)
                        paths.Add(s);

                    return HitTestFilterBehavior.Continue;

                });

            VisualTreeHelper.HitTest(MyCanvas, filterCallback, resultCallback, htp);

            // Set the label visibility based on whether or not we hit the line

            var line  = paths.FirstOrDefault();
            MyLabel.Visibility =  ReferenceEquals(line, MyLine) ? Visibility.Visible : Visibility.Collapsed;
        }
        private void MyCanvas_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (null == _path)
                return; 

            e.Handled = true;
            MyLabel.Visibility = Visibility.Collapsed;
            MyCanvas.Children.Remove(_path);
            _path = null;

            if (MyCanvas.IsMouseCaptured)
                MyCanvas.ReleaseMouseCapture();

        }
    }
}

您的代码中的问题是您没有正确使用命中测试回调。过滤器回调用于从命中测试中排除对象。结果回调为您提供有关实际测试被击中的信息。

但是,出于某种原因,您正在使用过滤器回调来记录命中测试的结果。这会产生无意义的结果。坦率地说,拖动的矩形和命中的测试对象之间存在任何关系只是巧合。这只是 WPF 具有的命中测试优化的产物。

以下是可以正常工作的回调实现:

var resultCallback = new HitTestResultCallback(
    r =>
    {
        if (r is GeometryHitTestResult g &&
            g.IntersectionDetail != IntersectionDetail.Empty &&
            g.IntersectionDetail != IntersectionDetail.NotCalculated &&
            g.VisualHit is Path p)
        {
            paths.Add(p);
        }

        return HitTestResultBehavior.Continue;
    });
var filterCallback = new HitTestFilterCallback(
    el =>
    {
        // Filter accepts any object of type Path.  There should be just one
        return string.IsNullOrEmpty((string)(el as Path)?.Tag) ?
            HitTestFilterBehavior.ContinueSkipSelf : HitTestFilterBehavior.Continue;

    });

在上面,结果回调验证交集是否已计算且非空,如果是,则检查命中的对象类型,如果是您期望的 Path 对象,则添加它到列表中。

过滤器回调简单地排除任何不是 Path 对象的对象。请注意,理论上,鉴于此实现,结果回调可以只转换 VisualHit 对象而不是使用 is。选择哪种方式主要是个人喜好问题。