I’m looking for a simple way to calculate the difference between two rectangles. I mean all points which belong to one of the rectangles, but not to both (so it’s like XOR).
The rectangles are axis-aligned in this case, so there will be only right angles. I believe the difference region can be expressed in 0-4 rectangles (0 if both rectangles are the same, 1 if just one edge is different, 4 in the general case), and I’d like to get the difference region as a list of rectangles.
You can also think of it as the areas of the screen that have to be updated when a solid rectangle is moved/resized.
Examples: Doubling the width of rectangle “a” – I want the added region (R).
+----+----+
| a | R |
| | |
+----+----+
Intersecting rectangles (a and b) – I want the area given by T, L, R and B in rectangles (other partitioning possible), but excluding X:
+------------+ a
| T |
|·····+------+-----+ b
| L | X | R |
| | | |
+-----+------+·····|
| B |
+------------+
I’d prefer a python solution/library, but any robust algorithm would be helpful.
Split the problem down onto a per-axis basis. Your rectangles can be defined in terms of their spans on each axis – find the interesting points on each axis where a rectangle starts or ends and then define your results in those terms. This’ll give you 6 rectangles of difference areas, you can easily combine them down to the four you’ve illustrated or eliminate degenerate zero-area rectangles if you need to.
Here’s a Java implementation: