Created
May 20, 2013 20:02
-
-
Save aspitz/5615051 to your computer and use it in GitHub Desktop.
UIImage category that adds a method to create a white image based on the source images alpha channel
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
@implementation UIImage (Alpha) | |
- (UIImage *)alphaImage{ | |
CGRect imageRect = CGRectMake(0, 0, self.size.width, self.size.height); | |
CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB(); // create an RGB Color Space | |
// create the context to do our drawing in | |
CGContextRef context = CGBitmapContextCreate(NULL, imageRect.size.width, imageRect.size.height, 8, imageRect.size.width * 4, rgbColorSpace, kCGImageAlphaPremultipliedLast); | |
// use the images alpha channel as a mask | |
CGContextClipToMask(context, imageRect, self.CGImage); | |
// set the fill color to be white | |
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0); | |
// paint the image white w/ the mask | |
CGContextFillRect(context, imageRect); | |
// convert the context to a CGImage | |
CGImageRef cgImage = CGBitmapContextCreateImage(context); | |
// convert the CGImage into a UIImage | |
UIImage *alphaImage = [UIImage imageWithCGImage:cgImage]; | |
// clean up | |
CGContextRelease(context); | |
CGColorSpaceRelease(rgbColorSpace); | |
CGImageRelease(cgImage); | |
// return the alpha image | |
return alphaImage; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment