Last active
August 29, 2017 19:32
-
-
Save stephsharp/51a5d44cca5541c19878 to your computer and use it in GitHub Desktop.
UIImage+Tint
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+Tint.h | |
// Created by Stephanie Sharp on 5/03/2014. | |
// | |
#import <UIKit/UIKit.h> | |
@interface UIImage (Tint) | |
- (UIImage *)translucentImageWithAlpha:(CGFloat)alpha; | |
- (UIImage *)tintedGradientImageWithColor:(UIColor *)tintColor; | |
- (UIImage *)tintedImageWithColor:(UIColor *)tintColor; | |
@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
// | |
// UIImage+Tint.m | |
// Created by Stephanie Sharp on 5/03/2014. | |
// | |
// See: http://stackoverflow.com/a/7543459/1367622 | |
// http://robots.thoughtbot.com/designing-for-ios-blending-modes | |
// | |
#import "UIImage+Tint.h" | |
@implementation UIImage (Tint) | |
#pragma mark - Public methods | |
// http://stackoverflow.com/a/7543459/1367622 | |
- (UIImage *)translucentImageWithAlpha:(CGFloat)alpha | |
{ | |
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0); | |
CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height); | |
[self drawInRect:bounds blendMode:kCGBlendModeScreen alpha:alpha]; | |
UIImage * translucentImage = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
return translucentImage; | |
} | |
- (UIImage *)tintedGradientImageWithColor:(UIColor *)tintColor | |
{ | |
return [self tintedImageWithColor:tintColor blendingMode:kCGBlendModeOverlay]; | |
} | |
- (UIImage *)tintedImageWithColor:(UIColor *)tintColor | |
{ | |
return [self tintedImageWithColor:tintColor blendingMode:kCGBlendModeDestinationIn]; | |
} | |
#pragma mark - Private methods | |
// http://robots.thoughtbot.com/designing-for-ios-blending-modes | |
- (UIImage *)tintedImageWithColor:(UIColor *)tintColor blendingMode:(CGBlendMode)blendMode | |
{ | |
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f); | |
[tintColor setFill]; | |
CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height); | |
UIRectFill(bounds); | |
[self drawInRect:bounds blendMode:blendMode alpha:1.0f]; | |
// if blend mode was overlay, restore image alpha | |
if (blendMode != kCGBlendModeDestinationIn) | |
[self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0]; | |
UIImage * tintedImage = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
return tintedImage; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also https://stackoverflow.com/a/7377827/1367622