Skip to content

Instantly share code, notes, and snippets.

@shanecowherd
Created January 14, 2020 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shanecowherd/2a16f730fd66ee262bb799cdd7a024a1 to your computer and use it in GitHub Desktop.
Save shanecowherd/2a16f730fd66ee262bb799cdd7a024a1 to your computer and use it in GitHub Desktop.
Change color of an image. A better approach is to use vector template images.
extension UIColor {
/// Change the color of a template image
/// Used in interface elements and icons
/// - Parameter tintColor: UIColor to tint
func imageWithColor(tintColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
tintColor.setFill()
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0, y: self.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.setBlendMode(CGBlendMode.normal)
let rect = CGRect(origin: .zero, size: CGSize(width: self.size.width, height: self.size.height))
context?.clip(to: rect, mask: self.cgImage!)
context?.fill(rect)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment