Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@alexruperez
Last active March 2, 2021 13:54
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save alexruperez/90f44545b57c25b977c4 to your computer and use it in GitHub Desktop.
Save alexruperez/90f44545b57c25b977c4 to your computer and use it in GitHub Desktop.
UIImage tint with UIColor in Swift
extension UIImage
{
func tint(color: UIColor, blendMode: CGBlendMode) -> UIImage
{
let drawRect = CGRectMake(0.0, 0.0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context = UIGraphicsGetCurrentContext()
CGContextClipToMask(context, drawRect, CGImage)
color.setFill()
UIRectFill(drawRect)
drawInRect(drawRect, blendMode: blendMode, alpha: 1.0)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage
}
}
func tint(image: UIImage, color: UIColor) -> UIImage
{
let ciImage = CIImage(image: image)
let filter = CIFilter(name: "CIMultiplyCompositing")
let colorFilter = CIFilter(name: "CIConstantColorGenerator")
let ciColor = CIColor(color: color)
colorFilter.setValue(ciColor, forKey: kCIInputColorKey)
let colorImage = colorFilter.outputImage
filter.setValue(colorImage, forKey: kCIInputImageKey)
filter.setValue(ciImage, forKey: kCIInputBackgroundImageKey)
return UIImage(CIImage: filter.outputImage)!
}
@cjg552
Copy link

cjg552 commented Nov 27, 2015

Hi Alex, great code. I have used the extension you wrote but I had to add this two lines after the context`s creation
// flip the image
CGContextScaleCTM(context, 1.0, -1.0)
CGContextTranslateCTM(context, 0.0, -self.size.height)
Because the final image appears flipped. Maybe it is useful for you.

Thanks!

@fabb
Copy link

fabb commented Dec 18, 2015

Here is a gist with an alternative implementation: https://gist.github.com/fabb/007d30ba0759de9be8a3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment