Mask UIImage in IOS

by / Monday, 30 September 2013 / Published in Ipad, Iphone

Bitmap images and image masks are like any drawing primitive in Quartz. Both images and image masks in Quartz are represented by the CGImageRef data type. As you’ll see later in this chapter, there are a variety of functions that you can use to create an image. Some of them require a data provider or an image source to supply bitmap data. Other functions create an image from an existing image either by copying the image or by applying an operation to the image. No matter how you create a bitmap image in Quartz, you can draw the image to any flavor of graphics context. Keep in mind that a bitmap image is an array of bits at a specific resolution. If you draw a bitmap image to a resolution-independent graphics context (such as a PDF graphics context) the bitmap is limited by the resolution at which you created it.

In .h file write the following code-

@property (retain, nonatomic) IBOutlet UIImageView *mainImage;

@property (retain, nonatomic) IBOutlet UIImageView *maskImage;

@property (retain, nonatomic) IBOutlet UIImageView *maskedImage;

- (IBAction)maskBtn:(id)sender;

In .m file inside your mask button on click write the following code-

UIImage * maskingImage=self.maskImage.image;
self.maskedImage.image=[self maskImage:self.mainImage.image withMask:maskingImage];

Now to mask one UIImage with another UIImage write the following method-

- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)mask_Image {

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//UIImage *maskImage = maskImage1;
CGImageRef maskImageRef = [mask_Image CGImage];

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

if (mainViewContentContext==NULL)
return NULL;

CGFloat widthratio = 0;
CGFloat heightratio = 0;

widthratio = mask_Image.size.width / image.size.width;
heightratio = mask_Image.size.height / image.size.height;

CGRect rect1 = {{0, 0}, {mask_Image.size.width, mask_Image.size.height}};
CGRect rect2 = {{-((image.size.width*widthratio)-mask_Image.size.width)/2 , -((image.size.height*heightratio)-mask_Image.size.height)/2}, {image.size.width*widthratio, image.size.height*heightratio}};

CGContextClipToMask(mainViewContentContext, rect1, maskImageRef);
CGContextDrawImage(mainViewContentContext, rect2, image.CGImage);

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

UIImage *theImage = [UIImage imageWithCGImage:newImage];


// return the image
return theImage;


for reference click here