Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS SDK - Image masking

How to mask an image with another image by non transparent pixels? E.g.

enter image description here

When the mask image is black&white, I use this function:

- (UIImage *)maskImage:(UIImage *)image 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([image CGImage], mask);
    return [UIImage imageWithCGImage:masked];
}

But how to do this in my case?

like image 313
arturdev Avatar asked May 06 '14 07:05

arturdev


1 Answers

Here are the steps, to achieve the result

1) Create an image view, and calculate the optimal size for it (+ set aspectFit option)

2) Get the image view frame, and create a mask with that options (i.e. scale your predefined mask image)

3) Mask image view, with your created mask

    UIImageView *maskView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"star_mask_alpha.png"]];
    self.needsMaskImageView.layer.mask = maskView.layer;
    [self.needsMaskImageView setNeedsDisplay];
like image 126
l0gg3r Avatar answered Oct 13 '22 21:10

l0gg3r