Last active
October 22, 2024 17:20
-
-
Save alexruperez/90f44545b57c25b977c4 to your computer and use it in GitHub Desktop.
UIImage tint with UIColor in Swift
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
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 | |
} | |
} |
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
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)! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is a gist with an alternative implementation: https://gist.github.com/fabb/007d30ba0759de9be8a3