9

I have an image in an UIScrollView, that can be scrolled and zoomed.

When the user presses a button, I want the code to create an image from whatever part of the UIScrollView is inside an area I specify with a CGRect.

I've seen code to crop UIImages, but I can't adapt it to do the same for a view, because it uses CGContextDrawImage.

Any thoughts?

Cheers, Andre

Andre
  • 4,417
  • 8
  • 32
  • 37

1 Answers1

28

I've managed to get it.

Here's my solution, based on a few different ones from the web:

- (UIImage *)imageByCropping:(UIScrollView *)imageToCrop toRect:(CGRect)rect
{
    CGSize pageSize = rect.size;
    UIGraphicsBeginImageContext(pageSize);

    CGContextRef resizedContext = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(resizedContext, -imageToCrop.contentOffset.x, -imageToCrop.contentOffset.y);
    [imageToCrop.layer renderInContext:resizedContext];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;
}

which you call by using:

CGRect clippedRect = CGRectMake(0, 0, 320, 300);
picture.image = [self imageByCropping:myScrollView toRect:clippedRect];
Andre
  • 4,417
  • 8
  • 32
  • 37
  • That was helpful, thanks. A little bug in the method, though: it refers to scrollView, although it should refer to imageToCrop instead, in case the caller does not name the view "scrollView". – Thomas Tempelmann May 20 '10 at 11:48
  • You're totally right :) I'm glad you found it useful though. Cheers – Andre May 20 '10 at 12:28
  • Great! Thanks :) but, how can I crop a image with resolution higher than 320*480. still need to process the orignal image? – Fourj Aug 16 '11 at 03:16
  • I've never tried it and I'm not an expert, but if you can't get it working with a size bigger than the screen, it COULD be because of the view's frame bounds. I'd change the size of the view to the dimensions you want, run the script and then change the size of the view again to the original dimensions. I might be completely wrong though. – Andre Sep 05 '11 at 11:28
  • I'm also using this way but it's loose the quality of the image a lot – Tien Nguyen Sep 03 '12 at 04:32
  • This seemed to be a bit off, until I discovered the `-73` on the y-coord in the `CGContextTranslateCTM` call :) Thanks, it works perfectly. – ThomasCle Jan 09 '13 at 13:18
  • Sorry, that was probably a very particular adjustment of mine. Think I had an overlay on top or something. Will edit it out ;) – Andre Jul 26 '13 at 21:27