简体   繁体   中英

How to remove the transparent area of an UIImageView after masking?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM