Last active
August 29, 2015 14:18
-
-
Save sdpjswl/b2c99068e327fb3b7812 to your computer and use it in GitHub Desktop.
Replace color of a UIImage with another color
This file contains hidden or 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+Colorize.h | |
// Coderwall | |
// | |
// Created by Coderwall on 11/04/15. | |
// Copyright (c) 2015 Coderwall. All rights reserved. | |
// | |
#import <UIKit/UIKit.h> | |
@interface UIImage (Colorize) | |
- (UIImage *)colorImageWithColor:(UIColor *)color; | |
@end |
This file contains hidden or 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+Colorize.m | |
// Coderwall | |
// | |
// Created by Coderwall on 11/04/15. | |
// Copyright (c) 2015 Coderwall. All rights reserved. | |
// | |
#import "UIImage+Colorize.h" | |
@implementation UIImage (Colorize) | |
- (UIImage *)colorImageWithColor:(UIColor *)color { | |
/** | |
* https://gist.github.com/1102091/b196c1ec001d1a69b9940f0f32043d62d5f596d4 | |
* https://coderwall.com/p/nne_ow/creating-colored-images-in-ios | |
*/ | |
// Make a rectangle the size of your image | |
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height); | |
// Create a new bitmap context based on the current image's size and scale, that has opacity | |
UIGraphicsBeginImageContextWithOptions(rect.size, NO, self.scale); | |
// Get a reference to the current context (which you just created) | |
CGContextRef c = UIGraphicsGetCurrentContext(); | |
// Draw your image into the context we created | |
[self drawInRect:rect]; | |
// Set the fill color of the context | |
CGContextSetFillColorWithColor(c, [color CGColor]); | |
// This sets the blend mode, which is not super helpful. Basically it uses the your fill color with the alpha of the image and vice versa. I'll include a link with more info. | |
CGContextSetBlendMode(c, kCGBlendModeSourceAtop); | |
// Now you apply the color and blend mode onto your context. | |
CGContextFillRect(c, rect); | |
// You grab the result of all this drawing from the context. | |
UIImage *result = UIGraphicsGetImageFromCurrentImageContext(); | |
// And you return it. | |
return result; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment