In one of my iOS applications, I am trying to cut a portion of an image using CGImageMask
. I have succeeded in masking the image with the following code:
- (UIImage *)maskImage:(UIImage *)referenceImage 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 masked = CGImageCreateWithMask([referenceImage CGImage], mask);
return [UIImage imageWithCGImage:masked];
}
So, my image will be:
myImageView.image = [self maskImage:[UIImage imageNamed:@"image.png"]
withMask:[UIImage imageNamed:@"mask.png"]];
Problem: The output image is of the same size of reference image('image.png') with transparent area around. But I want to avoid those transparent area, and crop the result image. How can I achieve this? There are several masks, and the mask frames are not similar to all. I am attaching a reference image of the problem overview here. Please help me friends. Thanks in advance.
Look up auto-cropping a UIImage. This should crop out anything transparent.
How do I autocrop a UIImage?