3

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.

enter image description here

Thampuran
  • 644
  • 5
  • 22

1 Answers1

6

Look up auto-cropping a UIImage. This should crop out anything transparent.

How do I autocrop a UIImage?

Community
  • 1
  • 1
Mark McCorkle
  • 9,349
  • 2
  • 32
  • 42
  • Wow...!!! Fast answer. Thank you very much. It is working great. I will surely accept your answer. But SO allows me to do so only after 4 mins. lol. :) – Thampuran Nov 11 '14 at 19:20