-
-
Save robmathers/01f007dfb36d55bb32d43a44e93b3f82 to your computer and use it in GitHub Desktop.
Swift UIImage extension to create arbitrarily-colored icons from a black-with-alpha master image
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
// | |
// ImageColourMask.swift | |
// | |
// Created by Rob Mathers on 2018-07-13. | |
// Swift version of https://gist.github.com/omz/1102091/e03982f00ecc34be6c40aedcb0932ed374992741 | |
// Original Objective-C version by Marco Arment and Ole Zorn | |
// | |
// Usage example: | |
// let maskedImage = UIImage(named: "test")?.maskedImage(color: UIColor.blue) | |
import UIKit | |
extension UIImage { | |
func maskedImage(color: UIColor) -> UIImage? { | |
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) | |
UIGraphicsBeginImageContextWithOptions(rect.size, false, self.scale) | |
let context = UIGraphicsGetCurrentContext() | |
self.draw(in: rect) | |
context?.setFillColor(color.cgColor) | |
context?.setBlendMode(CGBlendMode.sourceAtop) | |
context?.fill(rect) | |
let result = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment