Search code examples
iosimagemask

How to mask images with images in ios?


I have a square image representing a thick circle surronded by white, and another square image representing a face. I want to mask the second image with the circle so that the final image is the thick circle having indise the face of the second image. How this can be achieved in objective c?


Solution

  • At the end i used this function

    + (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage
    {
        CGImageRef imgRef = [image CGImage];
        CGImageRef maskRef = [maskImage CGImage];
        CGImageRef actualMask = CGImageMaskCreate(
                                              CGImageGetWidth(maskRef),
                                              CGImageGetHeight(maskRef),
                                              CGImageGetBitsPerComponent(maskRef),
                                              CGImageGetBitsPerPixel(maskRef),
                                              CGImageGetBytesPerRow(maskRef),
                                              CGImageGetDataProvider(maskRef), NULL, false);
        CGImageRef masked = CGImageCreateWithMask(imgRef, actualMask);
        return [UIImage imageWithCGImage:masked];
    }
    

    and this code

    // Getting an image imgResult that is center of imgToBeMasked with the surrounding transparent
    NSString *filePath_imgCircleMask = [[NSBundle mainBundle] pathForResource:@"imgCircleMask" ofType:@"png"];
    NSString *filePath_imgToBeMasked = [[NSBundle mainBundle] pathForResource:@"imgToBeMasked" ofType:@"png"];
    NSString *filePath_imgCircleHole = [[NSBundle mainBundle] pathForResource:@"imgCircleHole" ofType:@"png"];
    UIImage *imgCircleMask = [UIImage imageWithContentsOfFile:filePath_imgCircleMask];
    UIImage *imgToBeMasked = [UIImage imageWithContentsOfFile:filePath_imgToBeMasked];
    UIImage *imgCircleHole = [UIImage imageWithContentsOfFile:filePath_imgCircleHole];
    UIImage *imgResult =[funzioni maskImage:imgToBeMasked withMask:imgCircleMask];
    
    // Merge imgResult with imgCircleHole so to obtain the img to be masked inside the circle
    CGSize size = CGSizeMake(imgResult.size.width, imgResult.size.height);
    UIGraphicsBeginImageContext(size);
    [imgCircleHole drawInRect:CGRectMake(0,0,size.width, size.height)];
    [imgResult drawInRect:CGRectMake(0,0,size.width, size.height)];
    finalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    Here are the images. Save them and open it to see the trasparency. (imgCircleMask is a white image on a white background here) imgCircleMask

    enter image description here

    imgCircleHole

    enter image description here

    imgToBeMasked

    enter image description here

    imgResult

    enter image description here

    finalImage

    enter image description here

    Hope helps somenone!