I'm not sure what you want to crop, but instead you want to mask the image. This is fairly easy to do, but in the end you will find that it works for some images and not for others. This is because you need to have the proper alpha channel in the image.
Here is the code I use that I got from stackoverflow. ( Transparency issue when converting UIView to UIImage )
CGImageRef CopyImageAndAddAlphaChannel(CGImageRef sourceImage) { CGImageRef retVal = NULL; size_t width = CGImageGetWidth(sourceImage); size_t height = CGImageGetHeight(sourceImage); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef offscreenContext = CGBitmapContextCreate(NULL, width, height, 8, 0, colorSpace, kCGImageAlphaPremultipliedFirst); if (offscreenContext != NULL) { CGContextDrawImage(offscreenContext, CGRectMake(0, 0, width, height), sourceImage); retVal = CGBitmapContextCreateImage(offscreenContext); CGContextRelease(offscreenContext); } CGColorSpaceRelease(colorSpace); return retVal; } - (UIImage*)maskImage:(UIImage *)image withMask:(UIImage *)maskImage { CGImageRef maskRef = maskImage.CGImage; CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef), CGImageGetHeight(maskRef), CGImageGetBitsPerComponent(maskRef), CGImageGetBitsPerPixel(maskRef), CGImageGetBytesPerRow(maskRef), CGImageGetDataProvider(maskRef), NULL, false); CGImageRef sourceImage = [image CGImage]; CGImageRef imageWithAlpha = sourceImage;
And you call it like this:
customImage = [customImage maskImage:customImage withMask:[UIImage imageNamed:@"CircularMask.png"]];
In this case, I use a circular mask to create a circular image. You will need to make an irregular mask to suit your needs.
Paul cezanne
source share