I tried the code from the first link:
- (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];
}
Initially it didn't work, because the mask image that I used was partially transparent. I recreated the mask image making sure than the entire image was either black or white and it worked.
I found the following information on another website, which led me to this conclusion:
NOTE: The mask image cannot have ANY transparency. Instead,
transparent areas must be white or some value between black and white.
The more towards black a pixel is the less transparent it becomes.
In case it's related to the code that you're using to load the image from the image picker, here's the code that I used to load the image and the mask:
-(IBAction)selectImageFromCameraRoll:(UIButton *)sender
{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
{
NSArray *media = [UIImagePickerController
availableMediaTypesForSourceType: UIImagePickerControllerSourceTypePhotoLibrary];
if ([media containsObject:(NSString*)kUTTypeImage] == YES) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[picker setMediaTypes:[NSArray arrayWithObject:(NSString *)kUTTypeImage]];
picker.delegate = self;
[self presentViewController:picker animated:YES completion:nil];
}
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops!"
message:@"This device does not have a photo library."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info valueForKey:UIImagePickerControllerMediaType];
if([mediaType isEqualToString:(NSString*)kUTTypeImage])
{
UIImage *photoTaken = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
self.imageView.image = [self maskImage:photoTaken withMask:[UIImage imageNamed:@"mask.png"]];
}
[picker dismissViewControllerAnimated:NO completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];
}
Here's a link to the mask image that I used:
mask.png Download and rename the file.