Skip to content

Instantly share code, notes, and snippets.

@robmathers
Forked from omz/gist:1102091
Last active July 13, 2018 22:03
Show Gist options
  • Save robmathers/01f007dfb36d55bb32d43a44e93b3f82 to your computer and use it in GitHub Desktop.
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
//
// 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