Question

I'm programming a game, and i need to detect intersections between two CGRects. To do this, i've no problem. I do like this :

CGRect rect1 = CGRectMake (x1, y1, a1, b1);
CGRect rect2 = CGRectMake (x2, y2, a2, b2);
if (CGRectIntersectsRect(rect1, rect2))
{
    //do some stuff...
}

So i've no problem. But i would if it was possible to know the precise point of intersection from this two CGRect ? And if it's possible, how to ?

Thanks !

Was it helpful?

Solution

Use the CGRectIntersection() function to get the common part of two intersecting rectangles. From the result of that function call, you can calculate the edges of the rectangle using the CGRectGet[Max|Min][X|Y]() functions.

OTHER TIPS

I think I'm trying to do the same thing your doing. I wanted to get the specific overlap between two rects. I found CGRectUnion to be super helpful as it gives the smallest rect containing the two rects. If the size is larger than your "max" then you know the rect is overlapping to the right or bottom. If the origin is negative then you know the rect is overlapping to the top or left. I wrote this function to give the resulting offset needed to correct the overlap.

CGPoint GetOffsetBetweenFrames(CGRect maxBounds, CGRect frame)
{
    CGRect frameUnion = CGRectUnion(maxBounds, frame);

    CGPoint offset = CGPointZero;
    if (CGRectGetMinX(frameUnion) < 0)
        offset.x = -frameUnion.origin.x;
    else if (CGRectGetWidth(frameUnion) > CGRectGetWidth(maxBounds))
        offset.x = -(CGRectGetWidth(frameUnion) - CGRectGetWidth(maxBounds));

    if (CGRectGetMinY(frameUnion) < 0)
        offset.y = -frameUnion.origin.y;
    else if (CGRectGetHeight(frameUnion) > CGRectGetHeight(maxBounds))
        offset.y = -(CGRectGetHeight(frameUnion) - CGRectGetHeight(maxBounds));

    return offset;
}

Oh, also quick edit: To apply the offset its as simple as:

offset = GetOffsetBetweenFrames(maxBounds, frame);
frame = CGRectOffset(frame, offset.x, offset.y);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top