How to remove transparent area of ​​UIImageView after masking?

In one of my iOS apps, I am trying to cut out a portion of an image using CGImageMask

. I was able to mask 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 would be:

myImageView.image = [self maskImage:[UIImage imageNamed:@"image.png"] 
                           withMask:[UIImage imageNamed:@"mask.png"]];

      

Problem: The output image is the same size of the reference image ("image.png") with a transparent area around it. But I want to avoid this transparent area and crop the result image. How can I achieve this? There are several masks, and masks masks are not like all. Here I am attaching a referenced image of the issue overview. Please help me friends. Thanks in advance.

enter image description here

+3


source to share


1 answer


Have a look at UIImage's automatic cropping. This should output something transparent.



How do I autocrop UIImage?

+5


source







All Articles