3

我想在某些形状上使用 WPF HitTest 功能而不在屏幕上显示它们。这可能吗?这段代码不像我预期的那样工作。我该如何进行这项工作?

[Test, Ignore, RequiresSTA]
public void VerifyFillContains()
{
    // make a simple triangle:
    var seg1 = new System.Windows.Media.LineSegment(new Point(0.2, 0.1), false);
    var seg2 = new System.Windows.Media.LineSegment(new Point(0.3, 0.8), false);
    var figure = new PathFigure(new Point(0.7, 0.5), new List<PathSegment>{seg1, seg2}, true);

    var sg = new PathGeometry();
    sg.Figures.Add(figure);

    if (sg.CanFreeze)
        sg.Freeze();

    // these don't work:
    Assert.IsFalse(sg.FillContains(new Point()));
    Assert.IsFalse(sg.FillContains(new Point(1.0, 1.0)));
    Assert.IsTrue(sg.FillContains(new Point(0.5, 0.5)));

    var path = new Path { Data = sg, Fill = Brushes.Black };
    path.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
    path.Arrange(new Rect(path.DesiredSize));

    // and these don't work:
    var result = VisualTreeHelper.HitTest(path, new Point(0.0, 0.0));
    Assert.IsFalse(result != null && Equals(result.VisualHit, path));
    result = VisualTreeHelper.HitTest(path, new Point(1.0, 1.0));
    Assert.IsFalse(result != null && Equals(result.VisualHit, path));
    result = VisualTreeHelper.HitTest(path, new Point(0.5, 0.5));
    Assert.IsTrue(result != null && Equals(result.VisualHit, path));
}
4

2 回答 2

1

命中测试基于元素的渲染,因此您应该测量和排列形状。例如

shape.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
shape.Arrange(new Rect(shape.DesiredSize));

或者您可以只使用几何的FillContains方法。例如

var result = shape.Data.FillContains(ToPoint(target));
于 2013-06-13T17:49:00.450 回答
-1

我认为您的 CreateWpfShapeFromList 必须将 AddVisualChild 方法实现到您的形状的视觉孩子。

因为我反映了 VisualTreeHelper 并发现 HitTest 在内部使用 GetVisualChild,所以试试我的解决方案。

于 2013-06-13T05:13:30.017 回答