Skip to content

Instantly share code, notes, and snippets.

@CodingMeSwiftly
Last active November 7, 2017 17:20
Show Gist options
  • Save CodingMeSwiftly/3e6c80ca1a5dd23f8f9866c730e1f1c7 to your computer and use it in GitHub Desktop.
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.
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