Subtract CGRect from CGRect — largest piece of one not containing the other

后端 未结 3 1591
不思量自难忘°
不思量自难忘° 2021-02-07 08:05

How I can substract one CGRect from another? I want the result R1 - R2 to be the largest subrectangle of R1 that does not intersect R2.

相关标签:
3条回答
  • 2021-02-07 08:46

    Your definition is fairly ambiguous, what says whether the subtraction is horizontal or vertical? I recommend using a combination of CGRectIntersection and CGRectDivide, along with specifying a direction to remove ambiguity.

    (not tested, or even compiled)

    CGRect rectSubtract(CGRect r1, CGRect r2, CGRectEdge edge) {
        // Find how much r1 overlaps r2
        CGRect intersection = CGRectIntersection(r1, r2);
    
        // If they don't intersect, just return r1. No subtraction to be done
        if (CGRectIsNull(intersection)) {
            return r1;
        }
    
        // Figure out how much we chop off r1
        float chopAmount = (edge == CGRectMinXEdge || edge == CGRectMaxXEdge)
                           ? intersection.size.width
                           : intersection.size.height;
    
        CGRect r3, throwaway;
        // Chop
        CGRectDivide(r1, &throwaway, &r3, chopAmount, edge);
        return r3;
    }
    
    0 讨论(0)
  • 2021-02-07 08:47

    Would probably go something like this:

    CGRect frame = CGRectMake(0, 0, 320, 480);
    float aWidth  = frame.size.width; /* say for instance 320 */
    float aHeight = frame.size.height; /* say for instance 480 */
    
    int final = aWidth - aHeight;
    NSLog(@"Should be -160, your answer: %i",final);
    
    0 讨论(0)
  • 2021-02-07 08:55
    CGRect newRect = CGRectMake(0, 0, rect2.size.width - rect1.size.width, rect2.size.height - rect1.size.height);
    

    In response to your illustration, this code I've given you here will do exactly what you want (assuming you don't care about the origin XY coordinates). I've looked through the docs for CGGeometry functions, and there doesn't seem to be a CGRectDifference or other such method defined. There is, however, CGRectUnion, but that does the opposite of what you are looking for.

    0 讨论(0)
提交回复
热议问题