Last active
November 7, 2017 17:20
-
-
Save CodingMeSwiftly/3e6c80ca1a5dd23f8f9866c730e1f1c7 to your computer and use it in GitHub Desktop.
Shows how to apply alpha masked tintColor to a UIImage in Swift 4.
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 tinted(with tintColor: UIColor) -> UIImage { | |
guard let cgImage = cgImage else { return self } | |
UIGraphicsBeginImageContextWithOptions(size, false, scale) | |
defer { UIGraphicsEndImageContext() } | |
guard let context = UIGraphicsGetCurrentContext() else { return self } | |
context.translateBy(x: 0, y: size.height) | |
context.scaleBy(x: 1, y: -1) | |
context.setBlendMode(.normal) | |
let rect = CGRect(origin: .zero, size: size) | |
context.clip(to: rect, mask: cgImage) | |
tintColor.setFill() | |
context.fill(rect) | |
guard var tintedImage = UIGraphicsGetImageFromCurrentImageContext() else { return self } | |
if capInsets != .zero { | |
tintedImage = tintedImage.resizableImage(withCapInsets: capInsets, resizingMode: resizingMode) | |
} | |
return tintedImage | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment