Search code examples
iosobjective-ccgrect

Sum of Two CGRect


how to get sum of two CGRect

CGRect requiredFirst = [firstName boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];

CGRect requiredLast = [lastName boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];

CGRect height = ???


Solution

  • Here's an example of a method that will do that:

    - (CGRect)combineFrames:(CGRect)frame1, f2:(CGRect)frame2{
        CGFloat x = frame1.origin.x + frame2.origin.x;
        CGFloat y = frame1.origin.y + frame2.origin.y;
        CGFloat width = frame1.size.width + frame2.size.width;
        CGFloat height = frame1.size.height + frame2.size.height;
    
        CGRect combinedFrame = CGRectMake(x, y, width, height);
        return combinedFrame;
    }
    

    This method just adds all four of the frame's aspects (x, y, width, height) together individually then reconstructs it and returns it. Use it like this:

    CGRect combinedFrame = [self combineFrames:requiredFirst, f2:requiredLast];
    CGFloat height = combinedFrame.size.height;