Created
May 29, 2019 21:29
-
-
Save jgsamudio/7f0d5a333ab539277c343650a5a30a9d to your computer and use it in GitHub Desktop.
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 | |
// CodeImage | |
// | |
// Created by Jonathan Samudio on 5/29/19. | |
// Copyright © 2019 Prolific Interactive. All rights reserved. | |
// | |
import Cocoa | |
class ViewController: NSViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let view = NSTextField(frame: NSRect(x: 0, y: 0, width: 100, height: 100)) | |
view.stringValue = "HELLO WORLD" | |
view.wantsLayer = true | |
view.layer?.backgroundColor = NSColor.red.cgColor | |
self.view.addSubview(view) | |
let pngData = view.data() | |
// Resources | |
// https://stackoverflow.com/questions/41386423/get-image-from-calayer-or-nsview-swift-3 | |
// https://stackoverflow.com/questions/5491403/saving-an-nsview-to-a-png-file | |
// https://stackoverflow.com/questions/17507170/how-to-save-png-file-from-nsimage-retina-issues | |
// https://stackoverflow.com/questions/29262624/nsimage-to-nsdata-as-png-swift | |
let openPanel = NSOpenPanel() | |
openPanel.allowsMultipleSelection = false | |
openPanel.canChooseDirectories = true | |
openPanel.canCreateDirectories = false | |
openPanel.canChooseFiles = false | |
openPanel.title = "Select a folder" | |
openPanel.begin { (result) -> Void in | |
if result == NSApplication.ModalResponse.OK { | |
do { | |
if var url = openPanel.directoryURL { | |
url.appendPathComponent("view.png") | |
print(url) | |
try pngData.write(to: url, options: .atomicWrite) | |
} | |
} catch { | |
print(error) | |
} | |
} | |
} | |
} | |
} | |
extension NSView { | |
/// Get `Data` representation of the view. | |
/// | |
/// - Parameters: | |
/// - fileType: The format of file. Defaults to PNG. | |
/// - properties: A dictionary that contains key-value pairs specifying image properties. | |
/// - Returns: `Data` for image. | |
func data(using fileType: NSBitmapImageRep.FileType = .png, | |
properties: [NSBitmapImageRep.PropertyKey : Any] = [:]) -> Data { | |
let imageRepresentation = bitmapImageRepForCachingDisplay(in: bounds)! | |
cacheDisplay(in: bounds, to: imageRepresentation) | |
return imageRepresentation.representation(using: fileType, properties: properties)! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment