Created
October 26, 2013 07:00
-
-
Save christianroman/7166181 to your computer and use it in GitHub Desktop.
Icon coloration at runtime
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
-(UIImage *) negativeImage | |
{ | |
UIGraphicsBeginImageContext(self.size); | |
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeCopy); | |
[self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)]; | |
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeDifference); | |
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(),[UIColor whiteColor].CGColor); | |
CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, self.size.width, self.size.height)); | |
UIImage *negativeImage = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
return negativeImage; | |
} | |
- (UIImage *) imageWithWhiteBackground | |
{ | |
UIImage *negative = [self negativeImage]; | |
UIGraphicsBeginImageContext(negative.size); | |
CGContextSetRGBFillColor (UIGraphicsGetCurrentContext(), 1, 1, 1, 1); | |
CGRect thumbnailRect = CGRectZero; | |
thumbnailRect.origin = CGPointZero; | |
thumbnailRect.size.width = negative.size.width; | |
thumbnailRect.size.height = negative.size.height; | |
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0, negative.size.height); | |
CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0); | |
CGContextFillRect(UIGraphicsGetCurrentContext(), thumbnailRect); | |
CGContextDrawImage(UIGraphicsGetCurrentContext(), thumbnailRect, negative.CGImage); | |
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
return newImage; | |
} | |
+ (UIImage *) image:(UIImage *)image withMaskColor:(UIColor *)color | |
{ | |
UIImage *formattedImage = [image imageWithWhiteBackground]; | |
CGRect rect = {0, 0, formattedImage.size.width, formattedImage.size.height}; | |
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0); | |
[color setFill]; | |
UIRectFill(rect); | |
UIImage *tempColor = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
CGImageRef maskRef = [formattedImage CGImage]; | |
CGImageRef maskcg = CGImageMaskCreate(CGImageGetWidth(maskRef), | |
CGImageGetHeight(maskRef), | |
CGImageGetBitsPerComponent(maskRef), | |
CGImageGetBitsPerPixel(maskRef), | |
CGImageGetBytesPerRow(maskRef), | |
CGImageGetDataProvider(maskRef), NULL, false); | |
CGImageRef maskedcg = CGImageCreateWithMask([tempColor CGImage], maskcg); | |
CGImageRelease(maskcg); | |
UIImage *result = [UIImage imageWithCGImage:maskedcg]; | |
CGImageRelease(maskedcg); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment