Last active
March 24, 2019 07:45
-
-
Save ingconti/4affb4ff86404b2d65635dc62e6296e9 to your computer and use it in GitHub Desktop.
colouring NSImage
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
// | |
// 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 | |
} | |
} |
Author
ingconti
commented
Mar 24, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment