Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use IntersectsWith method with a rectangle defined in XAML

I have this rectangle in XAML :

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

I want to check if it intersects with another rectangle. In this question on SO, they say that one have to use the IntersectsWith method. But I'm unable to use it in code-behind. When I write in C# :

MyRectangle.IntersectsWith(

I get the standard error:

"System.Windows.Shapes.Rectangle does not contain a definition for 'IntersectsWith' and no extension method [...]"

I think that's because the rectangle in XAML is a System.Windows.Shapes.Rectangle, and the method is for System.Windows.Rect? If so, is there a way to "transform" my Rectangle into a Rect?

like image 904
Michaël Polla Avatar asked Jul 14 '13 00:07

Michaël Polla


3 Answers

Here's the solution I finally used. For each element I want to test if it intersects with others, I create a Rect containing it. Thus, I can use the IntersectsWith method.

Example (with rectangles, but you can do this with other figures, UserControls,...) : 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
}
like image 137
Michaël Polla Avatar answered Oct 07 '22 21:10

Michaël Polla


Try it

MyRectangle.RenderedGeometry.Bounds.IntersectsWith();
like image 44
Nitesh Avatar answered Oct 07 '22 21:10

Nitesh


you can use VisualTreeHelper.HitTest to test intersection don`t forget to set 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.

like image 41
makc Avatar answered Oct 07 '22 21:10

makc