Created
April 23, 2011 01:34
-
-
Save dimitribouniol/938107 to your computer and use it in GitHub Desktop.
iOS UIImage Masking!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <UIKit/UIKit.h> | |
@interface UIImage (DBMaskedImageAdditions) | |
- (UIImage *)maskedImageWithMask:(UIImage *)maskImage; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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