0

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;
    }
}
Alex Cio
  • 6,014
  • 5
  • 44
  • 74
Niels
  • 583
  • 5
  • 20
  • possible duplicate of [CGRectContainsRect Not Working](http://stackoverflow.com/questions/8981931/cgrectcontainsrect-not-working) – Palpatim Apr 23 '14 at 14:52
  • 1
    this isn't an issue that can be solved with CGRectContainsRect(), because the transformed rect of the image view can be rotated. i.e. it can't be expressed with a CGRect – Niels Apr 23 '14 at 15:01

1 Answers1

1

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;
}
Alex Cio
  • 6,014
  • 5
  • 44
  • 74
lead_the_zeppelin
  • 2,017
  • 13
  • 23
  • I hadn't thought of using a NSBezierPath (or UIBezierPath in my case). good idea, thanks! – Niels Apr 23 '14 at 16:41