Given rectangle_A intersecting rectangle_B, which has a union defined such that it is the rectangle containing both rectangles, I want to determine the coordinates of the (not overlapping) rectangles required to add to rectangle_A to create the union of rectangle_A and rectangle_B:
Note: this is just one configuration of the solution set of rectangles. the white rectangles above could be configured differently, as long as they don’t overlap.
Is there a simple algorithm for every case of rectangle intersection? I’ve done a first pass and I miss some corners. Evidently not my forté.
Why? When panning in a UI, I only want to (i) update the new parts of the canvas (ii) keep track of what has been painted as a rectangle (the union of rectangle_A and rectangle_B).
If you are not concerned with minimizing the number of rectangles returned, you can simplify the thought process to one that always returns no more than 8 rectangles:
If you wanted, you could then quickly check each rectangle to see if
r.x1 == r.x2 || r.y1 == r.y2(i.e. if it has zero area), and throw it out if so. In most cases, over half of the rectangles can be thrown out this way.For example, in your three examples, this solution would return 3, 1, and 5 rectangles, and would return 0 in the best case (when B is contained in A) and 8 in the worst case (when A is contained in B).