Check if rectangles intersect in Canvas XAML

I have a canvas in which I draw different rectangles. I have the coordinates of the rectangle in the collection. Every time a rectangle is added to the canvas, I need to check if it intersects another existing rectangle. I am checking a new rectangle with every existing rectangle in the canvas to see if the rectangle overlaps with any other rectangle. Is this the most effective solution?

foreach(System.Windows.Shapes.Rectangle r in rectCollection)
            {
                IntersectionDetail d1 = r.RenderedGeometry.FillContainsWithDetail(this.rect.RenderedGeometry);
                if(d1 == IntersectionDetail.Intersects)
                {
                    MessageBox.Show("New Rectangle intersects with existing rectangle");
                }

            }
+4
source share
1 answer

, , , , ; . , O(n).

, , LINQ .Any(), , ( , O(1)).

- " ", , , . .

, , Rect newRect, :

if (coordinates.Any(c => c.IntersectsWith(newRect)))
{
    //There is overlapping
}

, " " , Rectangle Windows.Shapes, . Rectangle , .

Rect , :

IEnumerable<Rect> coordinates = rectCollection.Select(r => new Rect(Canvas.GetLeft(r), Canvas.GetTop(r), r.Width, r.Height));

, ( , ifs lamdas ):

public static class Extensions
{
    public static bool InteriorIntersectsWith(this Rect rect, Rect other)
    {
        return rect.IntersectsWith(other) && IsIntersectingInside(rect, other);
    }

    private static bool IsIntersectingInside(Rect rect, Rect other)
    {
        Rect intersectionArea = Rect.Intersect(rect, other);
        return intersectionArea.Width > 0 && intersectionArea.Height > 0;
    }
}

, , , , . , , .

,

if (coordinates.Any(c => c.InteriorIntersectsWith(newRect)))
{
    //There is overlapping
}
+3

Source: https://habr.com/ru/post/1542253/


All Articles