Skip to content

Instantly share code, notes, and snippets.

@TiagoBras
Created September 10, 2017 18:34
Show Gist options
  • Select an option

  • Save TiagoBras/810755e3250fdbc2980a17e0edd13104 to your computer and use it in GitHub Desktop.

Select an option

Save TiagoBras/810755e3250fdbc2980a17e0edd13104 to your computer and use it in GitHub Desktop.
iOS - Masking a UIImage with color
// Swift 4
extension UIImage {
func maskWith(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
color.setFill()
draw(in: rect)
UIBezierPath(rect: rect).fill(with: .sourceIn, alpha: 1.0)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
// iOS 10+
extension UIImage {
func maskWith(color: UIColor) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { (context) in
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
color.setFill()
draw(in: rect)
UIBezierPath(rect: rect).fill(with: .sourceIn, alpha: 1.0)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment