Created
September 10, 2017 18:34
-
-
Save TiagoBras/810755e3250fdbc2980a17e0edd13104 to your computer and use it in GitHub Desktop.
iOS - Masking a UIImage with color
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
| // 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