Skip to content

Instantly share code, notes, and snippets.

@dimitribouniol
Created April 23, 2011 01:34
Show Gist options
  • Save dimitribouniol/938107 to your computer and use it in GitHub Desktop.
Save dimitribouniol/938107 to your computer and use it in GitHub Desktop.
iOS UIImage Masking!
#import <UIKit/UIKit.h>
@interface UIImage (DBMaskedImageAdditions)
- (UIImage *)maskedImageWithMask:(UIImage *)maskImage;
@end
#import "UIImage+DBMaskedImageAdditions.h"
@implementation UIImage (DBMaskedImageAdditions)
- (UIImage *)maskedImageWithMask:(UIImage *)maskImage
{
CGImageRef maskImageRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskImageRef),
CGImageGetHeight(maskImageRef),
CGImageGetBitsPerComponent(maskImageRef),
CGImageGetBitsPerPixel(maskImageRef),
CGImageGetBytesPerRow(maskImageRef),
CGImageGetDataProvider(maskImageRef), NULL, false);
CGImageRef sourceImage = self.CGImage;
CGImageRef maskedImage;
CGImageAlphaInfo alpha = CGImageGetAlphaInfo(sourceImage);
if (alpha != kCGImageAlphaFirst && alpha != kCGImageAlphaLast && alpha != kCGImageAlphaPremultipliedFirst && alpha != kCGImageAlphaPremultipliedLast) {
size_t width = CGImageGetWidth(sourceImage);
size_t height = CGImageGetHeight(sourceImage);
CGContextRef offscreenContext = CGBitmapContextCreate(NULL, width, height,
8, 0, CGImageGetColorSpace(sourceImage),
kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(offscreenContext, CGRectMake(0, 0, width, height), sourceImage);
CGImageRef imageRefWithAlpha = CGBitmapContextCreateImage(offscreenContext);
maskedImage = CGImageCreateWithMask(imageRefWithAlpha, mask);
CGImageRelease(imageRefWithAlpha);
CGContextRelease(offscreenContext);
} else {
maskedImage = CGImageCreateWithMask(sourceImage, mask);
}
UIImage *returnImage = [UIImage imageWithCGImage:maskedImage];
CGImageRelease(maskedImage);
CGImageRelease(mask);
return returnImage;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment