Thursday, August 25, 2011

How to divide a CGRect using CGRectDivide























 If you have a rectangle and you want to cut a slice of 40 px from the bottom edge. Following code will solve your problem. In the output,you will get dimension of your slice rectangle as well as reminder rectangle. Note: You can change the pixel amount (40 px) of your slice to any valid number of pixel and also change the edge to either of CGRectMinXEdge,CGRectMaxXEdge,CGRectMinYEdge,CGRectMaxYEdge


    CGRect b=CGRectMake(40, 50, 240, 150);
    
    
    CGRect remainder, slice;
    CGRectDivide(b, &slice, &remainder, 40, CGRectMaxYEdge);

    NSLog(@"(%.0f,%.0f,%.0f,%.0f)",CGRectGetMinX(remainder),CGRectGetMinY(remainder),CGRectGetWidth(remainder),CGRectGetHeight(remainder));
//It will give output= (40,50,240,110)

    NSLog(@"(%.0f,%.0f,%.0f,%.0f)",CGRectGetMinX(slice),CGRectGetMinY(slice),CGRectGetWidth(slice),CGRectGetHeight(slice));
//It will give output=(40,160,240,40)
    

    

If this is not what you were looking for CGRect, try this comprehensive LIST.

2 comments:

  1. NSLog(@"%@", NSStringFromCGRect(remainder));
    NSLog(@"%@", NSStringFromCGRect(slice));

    More clear logging.

    ReplyDelete
  2. i was trying to use an png file to make an reck divide for my brick break game. but this code seems like to be used by the reck which is made by using CGReckMake...what can I do?

    ReplyDelete