Posted at

Create new iOS system UIImages by tinting any source image

Convert an image asset of any color to appear like a Apple system icon, with these easy extensions. Use icons with no transparent backgrounds for best results!

First, add the familiar "Apple blue" color

extension UIColor {

class func rgb(r: Int, g: Int, b: Int, alpha: CGFloat) -> UIColor{
return UIColor(
red: CGFloat(r) / 255.0,
green: CGFloat(g) / 255.0,
blue: CGFloat(b) / 255.0,
alpha: alpha)
}

class func rgb(r: Int, g: Int, b: Int) -> UIColor{
return self.rgb(r: r, g: g, b: b, alpha: 1.0)
}

class var appleBlue: UIColor {
get {
return UIColor.rgb(r: 0, g: 122, b: 255)
}
}
}

Then use it with this handy tint extension

extension UIImage {

func tint(with color: UIColor) -> UIImage
{
UIGraphicsBeginImageContext(self.size)
guard let context = UIGraphicsGetCurrentContext() else { return self }
context.scaleBy(x: 1.0, y: -1.0)
context.translateBy(x: 0.0, y: -self.size.height)
context.setBlendMode(.multiply)

let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
context.clip(to: rect, mask: self.cgImage!)
color.setFill()
context.fill(rect)
guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else { return self }
UIGraphicsEndImageContext()
return newImage
}
}