Skip to content

Instantly share code, notes, and snippets.

@stephsharp
Created March 22, 2015 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephsharp/85ef559e16a5556a2f36 to your computer and use it in GitHub Desktop.
Save stephsharp/85ef559e16a5556a2f36 to your computer and use it in GitHub Desktop.
#import <UIKit/UIKit.h>
@interface UIImage (Tint)
- (UIImage *)translucentImageWithAlpha:(CGFloat)alpha;
- (UIImage *)tintedGradientImageWithColor:(UIColor *)tintColor;
- (UIImage *)tintedImageWithColor:(UIColor *)tintColor;
@end
#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