Skip to content

Instantly share code, notes, and snippets.

@ingconti
Last active March 24, 2019 07:45
Show Gist options
  • Save ingconti/4affb4ff86404b2d65635dc62e6296e9 to your computer and use it in GitHub Desktop.
Save ingconti/4affb4ff86404b2d65635dc62e6296e9 to your computer and use it in GitHub Desktop.
colouring NSImage
//
// ViewController.swift
// NSImageColoring
//
// Created by ing.conti on 21/03/2019.
// Copyright © 2019 ing.conti. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var original: NSImageView!
@IBOutlet weak var tinted: NSImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let img = NSImage(named: "stackoverflow")
let tintedImg = img?.tint(with: NSColor.white)
self.original.image = img
self.tinted.image = tintedImg
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
extension NSImage {
func tint(with color: NSColor) -> NSImage {
// make a copy, otherwise change the same image (i.e. self)
// for efficiency You can also use "self" directly replacing "copy" with "self".
let copy = self.copy() as! NSImage
copy.lockFocus()
color.set()
let srcSpacePortionRect = NSRect(origin: CGPoint(), size: self.size)
srcSpacePortionRect.fill(using: .sourceAtop)
copy.unlockFocus()
return copy
}
}
@ingconti
Copy link
Author

Screenshot 2019-03-24 at 08 43 38

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