Search code examples
c#.netsystem.drawing

Am I fundamentally misunderstanding the IntersectsWith function, or the Rectangles class/constructor?


I'm trying to write some code for a challenge calculating the total area of an array of rectangles, and subtracting the area of their overlaps. I was thinking of using System.Drawing.Rectangles and a custom IEqualityComparer to use GroupBy to group them into rectangles that intersect with each other, but I've hit a snag with something more basic, in that the IntersectsWith method is only returning true when the rectangles are identical, and Intersect is giving what seem to be inaccurate results:

var a = new Rectangle(0,1,1,1); //1x1 square with top left at (0,1)
var b = new Rectangle(0,2,2,2); //2x2 square with top left at (0,2)
var c = Rectangle.Intersect(a,b);// should have an intersect = the first rectangle **if I understand it correctly**
Console.WriteLine(c); //=> {X=0,Y=2,Width=1,Height=0}

Is there any way to check if this is being overridden somewhere in the test suite? Or am I just approaching this in an ignorant way?


Solution

  • the Intersection is correct:

    Image

    The first rectangle (red) and the second rectangle (green) do have exactly this 0-height rectangle, that is marked yellow in common.

    if you want to know if there is a non-empty intersection, then you should intersect and check the area to be > 0.