How to mask a UIImage in iOS

Mask UIImage iOS Santiapps.com by Marcio Valenzuela
Mask UIImage iOS Santiapps.com by Marcio Valenzuela

– (void)viewDidLoad
{
[super viewDidLoad];
UIImage *imageToMask = [UIImage imageNamed:@”koko.jpg”];
UIImageView *imageToMaskImgView = [[UIImageView alloc] initWithImage:imageToMask];
CGRect imgRect = CGRectMake(0, 0, imageToMaskImgView.frame.size.width, imageToMaskImgView.frame.size.height);
UIView *maskMaster = [[UIView alloc] initWithFrame:imgRect];
[maskMaster setBackgroundColor:[UIColor whiteColor]];
[maskMaster addSubview:imageToMaskImgView];
UIGraphicsBeginImageContext(maskMaster.bounds.size);
[maskMaster.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSLog(@”%@ is the view image”, viewImage);
UIImage *bFooImg = [UIImage imageNamed:@”blackapple.png”];
self.myPic.image = [self maskImage:bFooImg withMask:viewImage];
}
– (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);
//memman
CGImageRelease(mask);
CGImageRelease(maskRef);
return [UIImage imageWithCGImage:masked];
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s