2

我正在尝试在画布上实现 WPF Path 对象的橡皮筋选择。不幸的是,我使用带有矩形几何形状的 VisualTreeHelper.HitTest 并没有像我预期的那样工作。

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

有什么办法可以解决这个问题或者我做错了什么?

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

在这里,我就在这条线上,正如我所料,它检测到了命中。这很好。

成功命中如预期

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

下线,没有命中

但每当我在左边或线上的任何地方,无论多远,我都会受到打击

在此处输入图像描述

这是测试应用程序窗口:

<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();

        }
    }
}
4

1 回答 1

1

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

但是,由于某种原因,您正在使用过滤器回调来记录命中测试的结果。这会产生毫无意义的结果。坦率地说,被拖动的矩形和命中测试对象之间根本没有任何关系只是巧合。这只是 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. 这主要是个人喜好的问题。

于 2019-09-30T02:55:11.390 回答