Skip to content

Instantly share code, notes, and snippets.

@usagimaru
Last active October 12, 2023 13:39
Show Gist options
  • Save usagimaru/c0a03ef86b5829fb9976b650ec2f1bf4 to your computer and use it in GitHub Desktop.
Save usagimaru/c0a03ef86b5829fb9976b650ec2f1bf4 to your computer and use it in GitHub Desktop.
NSImage+TintColor
import Cocoa
// This will work with Swift 5
extension NSImage {
func image(with tintColor: NSColor) -> NSImage {
if self.isTemplate == false {
return self
}
let image = self.copy() as! NSImage
image.lockFocus()
tintColor.set()
let imageRect = NSRect(origin: .zero, size: image.size)
imageRect.fill(using: .sourceIn)
image.unlockFocus()
image.isTemplate = false
return image
}
}
/* Usage
let sourceImage = NSImage(named: NSImage.Name("ImageName"))!
sourceImage.isTemplate = true
let tintColor = NSColor(red: 1.0, green: 0.08, blue: 0.50, alpha: 1.0)
let coloredImage = sourceImage.image(with: tintColor)
imageView.image = coloredImage
*/
@Cyberbeni
Copy link

.CompositeSourceIn works better for colors with not 100% alpha

@robinstewart
Copy link

Swift 5 needs:

    let imageRect = NSRect(origin: .zero, size: image.size)
    imageRect.fill(using: .sourceAtop)

@usagimaru
Copy link
Author

@Cyberbeni @robinstewart
Thanks for some advices!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment