Created
March 22, 2015 10:45
-
-
Save mdales/6b97ff366f210d741178 to your computer and use it in GitHub Desktop.
Script in swift to write a view out to a TIFF file
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
#!/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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The mymain is a hack, as otherwise any vars in your script are global, and then accessibile from anywhere (which makes me sad)