Niels
Niels

Reputation: 583

Check if CGRect is contained within another (transformed) rect

I'm implementing a cropping feature and I'm trying to figure out how to test whether the crop rectangle is fully contained within the transformed image view. i.e. there should be no whitespace in the cropped portion of the image.

I've tried to copy the behavior as implemented in this component: https://github.com/heitorfr/ios-image-editor, which implements a similar check (see below), but I can't get it to work for my situation.

- (void)checkBoundsWithTransform:(CGAffineTransform)transform
{
    CGRect r1 = [self boundingBoxForRect:self.preview.cropRect 
                        rotatedByRadians:[self imageRotation]];
    Rectangle r2 = [self applyTransform:transform 
                                 toRect:self.preview.initialImageFrame];

    CGAffineTransform t = 
     CGAffineTransformMakeTranslation(CGRectGetMidX(self.preview.cropRect), 
                                      CGRectGetMidY(self.preview.cropRect));
    t = CGAffineTransformRotate(t, -[self imageRotation]);
    t = CGAffineTransformTranslate(t, 
                                   -CGRectGetMidX(self.preview.cropRect), -
                                   CGRectGetMidY(self.preview.cropRect));

    Rectangle r3 = [self applyTransform:t toRectangle:r2];

    if(CGRectContainsRect([self CGRectFromRectangle:r3],r1)) {
        self.validTransform = transform;
    }
}

Upvotes: 0

Views: 1446

Answers (1)

lead_the_zeppelin
lead_the_zeppelin

Reputation: 2052

Not the most performant solution, but very quick and dirty-ish.

NSBezierPath *path = [NSBezierPath bezierPathWithRect:r2];
[path transformUsingAffineTransform:t];
if([path containsPoint:NSMinX(r1)] 
    && [path containsPoint:NSMinY(r1)] 
    && [path containsPoint:NSMaxX(r1)] 
    && [path containsPoint:(NSMaxY(r1)] ){
    self.validTransform = transform;
}

Upvotes: 1

Related Questions