Skip to content

Instantly share code, notes, and snippets.

@hankbao
Created March 19, 2013 07:24
Show Gist options
  • Save hankbao/5194309 to your computer and use it in GitHub Desktop.
Save hankbao/5194309 to your computer and use it in GitHub Desktop.
Chop a rectangle from another rectangle on iOS
static
void divide_rect_from_rects(CGRect rect1, CGRect rect2, CGRect *slice, CGRect *remainder, CGRectEdge edge)
{
NSCParameterAssert(slice);
NSCParameterAssert(remainder);
CGRect intersected = CGRectIntersection(rect1, rect2);
if (CGRectIsEmpty(intersected)) {
*slice = CGRectNull;
return;
}
CGFloat chop;
switch (edge) {
case CGRectMinYEdge: chop = fabs(CGRectGetMinY(intersected) - CGRectGetMinY(rect1)); break;
case CGRectMaxYEdge: chop = fabs(CGRectGetMaxY(rect1) - CGRectGetMaxY(intersected)); break;
case CGRectMinXEdge: chop = fabs(CGRectGetMinX(intersected) - CGRectGetMinX(rect1)); break;
case CGRectMaxXEdge: chop = fabs(CGRectGetMaxX(rect1) - CGRectGetMaxX(intersected)); break;
default: NSCAssert(0, @"invalid CGRectEdge value"); break;
}
CGRectDivide(rect1, slice, remainder, chop, edge);
return;
}
- (NSArray *)rectsFromRect:(CGRect)rect1 chopRect:(CGRect)rect2
{
if (CGRectIsEmpty(rect1))
return @[];
CGRect intersected = CGRectIntersection(rect1, rect2);
if (CGRectIsEmpty(intersected))
return [NSArray arrayWithObject:NSStringFromCGRect(rect1)];
NSMutableArray *rects = [NSMutableArray array];
CGRect slice, remainder;
slice = remainder = CGRectNull;
divide_rect_from_rects(rect1, intersected, &slice, &remainder, CGRectMinYEdge);
if (!CGRectIsEmpty(slice))
[rects addObject:NSStringFromCGRect(slice)];
divide_rect_from_rects(remainder, intersected, &slice, &remainder, CGRectMaxYEdge);
if (!CGRectIsEmpty(slice))
[rects addObject:NSStringFromCGRect(slice)];
divide_rect_from_rects(remainder, intersected, &slice, &remainder, CGRectMinXEdge);
if (!CGRectIsEmpty(slice))
[rects addObject:NSStringFromCGRect(slice)];
divide_rect_from_rects(remainder, intersected, &slice, &remainder, CGRectMaxXEdge);
if (!CGRectIsEmpty(slice))
[rects addObject:NSStringFromCGRect(slice)];
return rects;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment