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

那年仲夏 提交于 2019-12-05 05:37:47

问题


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.


回答1:


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

How do I autocrop a UIImage?



来源:https://stackoverflow.com/questions/26872568/how-to-remove-the-transparent-area-of-an-uiimageview-after-masking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!