I wrote an application that does this pretty well, it's called QColor - send me a request for a promo code if you want to see it.
In my experience, the iPhone stopped updating live using an inefficient algorithm. This is what I settled in (pseudo-code - sorry, the full source has many other things).
It should be noted that this algorithm contains multiple overlapping rectangles, so when you refresh the screen, you need to display SubviewToFront: at the intersections with most rectangles.
NSArray intersections; // each Intersection is an array of rectangles with a calculated rect - contact me if you want code that can do this (it not glorious). - (void) addRect: newRect { intersections addObject: newRect; for (Intersection *intersection in intersections) { if (intersection intersects newRect) { create new intersection of intersection + newRect // note, do NOT modify the intersection - add a NEW one. Important point. } } } - (void) removeRect: aRect { remove every intersection that contains aRect - careful, don't use fast enumeration while editing the data structure. } - (void) moveRect: aRect { for (Intersection *intersection in intersections) { if (intersection contains aRect) { recompute the intersection with the moved aRect. If ANY rectangle no longer intersects, delete the entire intersection (compare count before and after recalculation) } else { if (intersection intersects newRect) { create new intersection of intersection + newRect } } } }
This is not as beautiful as the recursive algorithm, but it is important that the total number of intersections is low. Now I first tried this with n! algorithm, so of course he suffocated. N ^ 2 above, I'm not sure if this will be adequate. As far as I understand, my algorithm goes through the order n each time, although some examples of the worst cases with everything overlapping (but not completely) may be n! (which is data, not an algorithm).
I have screenshots on the page of my application if you want to render the rectangles: http://itunes.apple.com/ph/app/qcolor/id490077718?mt=8
Done - sorry for any typos!
Damien
source share