【问题标题】:How to use IntersectsWith method with a rectangle defined in XAML如何将 IntersectsWith 方法与 XAML 中定义的矩形一起使用
【发布时间】:2013-07-14 00:10:13
【问题描述】:

我在 XAML 中有这个矩形:

<Rectangle x:Name="MyRectangle" Height="300" Width="300"></Rectangle>

我想检查它是否与另一个矩形相交。在this question on SO 中,他们说必须使用IntersectsWith method。 但我无法在代码隐藏中使用它。当我用 C# 编写时:

MyRectangle.IntersectsWith(

我得到标准错误:

“System.Windows.Shapes.Rectangle 不包含 'IntersectsWith' 的定义并且没有扩展方法 [...]”

我认为这是因为XAML中的矩形是System.Windows.Shapes.Rectangle,而方法是System.Windows.Rect?如果是这样,有没有办法将我的Rectangle“转换”为Rect

【问题讨论】:

    标签: wpf xaml hittest rectangles


    【解决方案1】:

    这是我最终使用的解决方案。 对于我想测试的每个元素是否与其他元素相交,我创建了一个包含它的 Rect。因此,我可以使用 IntersectsWith 方法。

    示例(使用矩形,但您可以使用其他图形、用户控件、...): XAML

    <Canvas>
        <Rectangle x:Name="Rectangle1" Height="100" Width="100"/>
        <Rectangle x:Name="Rectangle2" Height="100" Width="100" Canvas.Left="50"/>
    </Canvas>
    

    C#

    Rect rect1 = new Rect(Canvas.GetLeft(Rectangle1), Canvas.GetTop(Rectangle1), Rectangle1.Width, Rectangle1.Height);
    Rect rect2 = new Rect(Canvas.GetLeft(Rectangle2), Canvas.GetTop(Rectangle2), Rectangle2.Width, Rectangle2.Height);
    if(rect1.IntersectsWith(r2))
    {
        // The two elements overlap
    }
    

    【讨论】:

      【解决方案2】:

      试试看

      MyRectangle.RenderedGeometry.Bounds.IntersectsWith();
      

      【讨论】:

      • 嗨!谢谢你的回复。我尝试了您的建议,但无法实现。我在画布上重叠了两个矩形,但是当我写:if(Rect1.RenderedGeometry.Bounds.IntersectsWith(Rect2.RenderedGeometry.Bounds)) 时,条件不是“真”。
      【解决方案3】:

      你可以使用VisualTreeHelper.HitTest来测试路口不要忘记设置GeometryHitTestParameters

      Windows Presentation Foundation (WPF) hit testing only considers the filled area of a geometry during a hit test. If you create a point Geometry, the hit test would not intersect anything because a point has no area.

      【讨论】:

      • 嗨!谢谢你的帮助。我几乎能够找到一个可行的解决方案,尤其是 GeometryHitTestParameters 文档提供的示例,但同时我找到了另一个更容易编写和理解的解决方案:)
      • @MichaëlPolla 欢迎 :),没有唯一正确的解决方案,如果 IntersectsWith 解决了问题,那么您就在正确的道路上 :) 您可以接受自己的答案 ;) 没有难过的感觉
      猜你喜欢
      • 1970-01-01
      • 2015-01-12
      • 2019-11-05
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 2012-04-10
      相关资源
      最近更新 更多