Last active
August 15, 2016 07:24
-
-
Save cypres/bd08a9a9aa5102ec33e3 to your computer and use it in GitHub Desktop.
Tinting UIImage with Overlay (preserving grey scale info)
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
import UIKit | |
extension UIImage { | |
func imageGreyScale() -> UIImage { | |
let imageRect = CGRectMake(0, 0, self.size.width, self.size.height) | |
let greyContext = CGBitmapContextCreate( | |
nil, UInt(self.size.width*self.scale), UInt(self.size.height*self.scale), | |
8, 0, | |
CGColorSpaceCreateDeviceGray(), | |
CGBitmapInfo.fromRaw(CGImageAlphaInfo.None.toRaw())! | |
) | |
let alphaContext = CGBitmapContextCreate( | |
nil, UInt(self.size.width*self.scale), UInt(self.size.height*self.scale), | |
8, 0, | |
nil, | |
CGBitmapInfo.fromRaw(CGImageAlphaInfo.Only.toRaw())! | |
) | |
CGContextScaleCTM(greyContext, self.scale, self.scale) | |
CGContextScaleCTM(alphaContext, self.scale, self.scale) | |
CGContextDrawImage(greyContext, imageRect, self.CGImage) | |
CGContextDrawImage(alphaContext, imageRect, self.CGImage) | |
let greyImage = CGBitmapContextCreateImage(greyContext) | |
let maskImage = CGBitmapContextCreateImage(alphaContext) | |
let combinedImage = CGImageCreateWithMask(greyImage, maskImage) | |
return UIImage(CGImage: combinedImage) | |
} | |
func imageWithOverlayTint(tintColor: UIColor) -> UIImage { | |
let greyImage = self.imageGreyScale() | |
UIGraphicsBeginImageContextWithOptions(self.size, false, 0) | |
let bounds = CGRectMake(0, 0, self.size.width, self.size.height) | |
greyImage.drawInRect(bounds) | |
tintColor.setFill() | |
UIRectFillUsingBlendMode(bounds, kCGBlendModeOverlay) | |
greyImage.drawInRect(bounds, blendMode: kCGBlendModeDestinationIn, alpha: 1.0) | |
let tintedImage = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return tintedImage | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment