Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Script in swift to write a view out to a TIFF file
#!/usr/bin/env xcrun swift
import Cocoa
// library code (one day)
func convertViewToTIFF(view: NSView) -> NSData? {
let application = NSApplication.sharedApplication()
let win = NSWindow(contentRect: view.bounds, styleMask: 0, backing: NSBackingStoreType.Nonretained, defer: false)
if let contentView: NSView = win.contentView as? NSView {
let rep = NSBitmapImageRep(focusedViewRect:view.bounds)
if let saferep = rep {
return saferep.TIFFRepresentation
return .None
// my logic
class MyView: NSView {
var backgroundColor : NSColor = NSColor.redColor();
override func drawRect(dirtyRect: NSRect) {
// script
func mymain() -> Void {
let test = MyView()
test.backgroundColor = NSColor.greenColor()
test.frame = NSMakeRect(0, 0, 300, 400)
if let tiffdata = convertViewToTIFF(test) {
tiffdata.writeToFile("/tmp/test.tiff", atomically: true)
} else {
println("Failed to render view")
test.backgroundColor = NSColor.blueColor()
test.frame = NSMakeRect(0, 0, 200, 200)
if let tiffdata = convertViewToTIFF(test) {
tiffdata.writeToFile("/tmp/test2.tiff", atomically: true)
} else {
println("Failed to render view")

This comment has been minimized.

Copy link
Owner Author

mdales commented Mar 22, 2015

The mymain is a hack, as otherwise any vars in your script are global, and then accessibile from anywhere (which makes me sad)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.