Skip to content

Instantly share code, notes, and snippets.

@mdales
Created March 22, 2015 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdales/6b97ff366f210d741178 to your computer and use it in GitHub Desktop.
Save mdales/6b97ff366f210d741178 to your computer and use it in GitHub Desktop.
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()
application.setActivationPolicy(NSApplicationActivationPolicy.Accessory)
let win = NSWindow(contentRect: view.bounds, styleMask: 0, backing: NSBackingStoreType.Nonretained, defer: false)
if let contentView: NSView = win.contentView as? NSView {
contentView.addSubview(view)
win.makeKeyAndOrderFront(nil)
view.lockFocus()
let rep = NSBitmapImageRep(focusedViewRect:view.bounds)
view.unlockFocus()
if let saferep = rep {
return saferep.TIFFRepresentation
}
}
return .None
}
// my logic
class MyView: NSView {
var backgroundColor : NSColor = NSColor.redColor();
override func drawRect(dirtyRect: NSRect) {
self.backgroundColor.set()
NSBezierPath.fillRect(dirtyRect)
}
}
// 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")
}
}
mymain()
@mdales
Copy link
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