Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

enter image description here

like image 614
Thampuran Avatar asked Dec 04 '25 17:12

Thampuran


1 Answers

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

How do I autocrop a UIImage?

like image 199
Mark McCorkle Avatar answered Dec 06 '25 07:12

Mark McCorkle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!