Masking of Image on another image

Here is a small core graphics method for masking of images:

 

– (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

CGContextRef mainViewContentContext;
CGColorSpaceRef colorSpace;

colorSpace = CGColorSpaceCreateDeviceRGB();

// create a bitmap graphics context the size of the image
mainViewContentContext = CGBitmapContextCreate (NULL, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);

// free the rgb colorspace
CGColorSpaceRelease(colorSpace);

CGImageRef maskingImage = [maskImage CGImage];
CGContextClipToMask(mainViewContentContext, CGRectMake(0, 0, maskImage.size.width, maskImage.size.height), maskingImage);
CGContextDrawImage(mainViewContentContext, CGRectMake(0, 0, image.size.width, image.size.height), self.CGImage);

// Create CGImageRef of the main view bitmap content, and then
// release that bitmap context
CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext);

// convert the finished resized image to a UIImage
UIImage *theImage = [UIImage imageWithCGImage:mainViewContentBitmapContext];
// image is retained by the property setting above, so we can
// release the original

CGContextRelease(mainViewContentContext);
CGImageRelease(mainViewContentBitmapContext);
maskingImage = nil;
CGImageRelease(maskingImage);
// return the image
return theImage;

}

For more detail about masking please checkout Quartz 2D developer guide:

http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_images/dq_images.html

 

!! Enjoy !!

This entry was posted in iOS by Muzammil. Bookmark the permalink.

About Muzammil

Hey Guys, I am Muzammil Mohammad. Having 7 years of experience in iOS development. I am here to share my knowledge with all mobile application developers and those companies who are stuck on development (due to bad quality of code or don't know what to do) or want to know how to build a good mobile app. I believe I am more expert in UI and Architecture design of mobile app. So if you need my helps or assistant for your mobile app projects, Feel free to contact me. I will try my best to improve the quality of your app. Or you can hire me to develop your apps. I’d love to talk with you. Best!

Leave a Reply

Your email address will not be published. Required fields are marked *