Search code examples
iosintersectioncgrect

amount of rect intersection?


i am trying to check the degree of overlap between 2 CGPaths. the easiest way i have come up with is get the percentage of the overlap between the bounding CGRects. I know this will fail when different paths occupy similar bounds. but oh well, if you know of a better way ... please help.

anyway, the current question regards calculating the percentage overlap between the rects. i see the CGRectIntersection function to obtain the rectangle of intersection. I can calculate the area of this rect, but there doesn't seem to be an easy way to get the area of the non-intersected regions. any ideas? would subtracting that area from the area of the rectUnion make sense? if i understand rectUnion correctly, if the union and the intersection are the same size, they completely overlap?


Solution

  • Not quite understanding, I think. Isn't the "non-intersecting region" of a CGRect A with another one B just A's area minus the intersecting region? Or more to the point, isn't the percentage overlap just equal to the intersecting area divided by the combined total area:

    Area(A ^ B)/(Area(A) + Area(B) - Area(A^B))
    

    (BTW, I don't think you want to deal with RectUnion as that potentially has a huge amount of space in neither A or B. )

    Oh, and on your original question, that's beyond my graphics ability, but the basic technique seems to be to draw both Paths in a graphic context (maybe with an XOR) and see which pixels are still left on. There seems to be some code pointing the way here: Clipping CGPath to a CGRect