Skip to content

Instantly share code, notes, and snippets.

@randomsequence
Created March 30, 2016 19:47
Show Gist options
  • Save randomsequence/ff044df3b758ccd425665c080c580717 to your computer and use it in GitHub Desktop.
Save randomsequence/ff044df3b758ccd425665c080c580717 to your computer and use it in GitHub Desktop.
Drawing to NSImage using Quartz in Swift
import Cocoa
// helper function which takes a size and a drawing function.
// returns an image
public func drawItems(bounds: CGRect, block: (bounds: CGRect, context: CGContextRef) -> () ) -> NSImage? {
var outputImage: NSImage? = nil
let insetSize = CGSizeMake(-20, -20)
let insetBounds = CGRectInset(bounds, insetSize.width, insetSize.height)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
let bitmapContext = CGBitmapContextCreate(
nil,
Int(insetBounds.size.width),
Int(insetBounds.size.height),
8,
0,
colorSpace,
bitmapInfo.rawValue)
if let context = bitmapContext {
CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-insetSize.width, -insetSize.height))
CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-bounds.origin.x, -bounds.origin.y))
block(bounds: bounds, context: context)
if let image = CGBitmapContextCreateImage(context) {
outputImage = NSImage(CGImage: image, size: insetBounds.size)
}
}
return outputImage
}
// example drawing function
func drawSquare(bounds: CGRect, context: CGContextRef) {
let path = CGPathCreateWithRect(bounds, nil)
CGContextAddPath(context, path)
CGContextSetStrokeColorWithColor(context, NSColor.redColor().CGColor)
CGContextSetLineWidth(context, 20)
CGContextSetLineJoin(context, CGLineJoin.Round)
CGContextSetLineCap(context, CGLineCap.Round)
let dashArray:[CGFloat] = [16, 32]
CGContextSetLineDash(context, 0, dashArray, 2)
CGContextReplacePathWithStrokedPath(context)
CGContextSetFillColorWithColor(context, NSColor.redColor().CGColor)
CGContextFillPath(context)
}
let bounds = CGRectMake(0, 0, 128, 128)
let image = drawItems(bounds, block: drawSquare)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment