0

I have been following this SO question to crop an UIImageView that is connected with IBOutlet with a Layer Mask, here is the question and answer I was following How to crop image inside the circle in UIImageView in iOS. But now I am wondering how this could be done without have a UIImageView shown to the user. (So one that is not connected to IBOutlet). I commented on the post and the user said to use core graphics to crop the image without having it connected. Im not sure how to do this? So I am wondering how to apply a crop to a UIImage or UIImageView with core Core Graphics?

Thanks for the help in advance.

Community
  • 1
  • 1
iqueqiorio
  • 1,149
  • 2
  • 35
  • 78

1 Answers1

0

You could, for example, do something like the following, which creates a bitmap context, adds a clipping path, draws an image into that context, and then extracts the image back out of that context:

NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"jpg"];
UIImage *image = [UIImage imageWithContentsOfFile:path];

size_t width = image.size.width, height = image.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = (CGBitmapInfo)kCGImageAlphaPremultipliedLast;
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 4 * width, colorSpace, bitmapInfo);

CGRect rect = ...
CGContextAddEllipseInRect(context, rect);
CGContextClip(context);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), image.CGImage);

CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage *final = [UIImage imageWithCGImage:imageRef];

NSData *data = UIImagePNGRepresentation(final);

NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *savePath      = [documentsPath stringByAppendingPathComponent:@"final.png"];

[data writeToFile:savePath atomically:YES];

CGColorSpaceRelease(colorSpace);
CGImageRelease(imageRef);
CGContextRelease(context);

For more information, see the Quartz 2D Programming Guide. Or refer to the CGContext Reference.

Rob
  • 415,655
  • 72
  • 787
  • 1,044