Skip to content

Instantly share code, notes, and snippets.

@westerlund
Forked from randomsequence/cocoa-drawing.swift
Last active November 29, 2015 10:33
Show Gist options
  • Save westerlund/c8aa6485967637dac54d to your computer and use it in GitHub Desktop.
Save westerlund/c8aa6485967637dac54d to your computer and use it in GitHub Desktop.
Drawing images with CGContext and NSGraphicsContext in Swift
//: Playground - noun: a place where people can play
import Cocoa
let bounds = CGRectMake(0, 0, 100, 100);
func DrawImageInCGContext(size: CGSize, drawFunc: (context: CGContextRef, rect: CGRect) -> Void) -> NSImage? {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
if let context = CGBitmapContextCreate(
nil,
Int(size.width),
Int(size.height),
8,
0,
colorSpace,
bitmapInfo.rawValue) {
drawFunc(context: context, rect: CGRect(origin: CGPoint.zero, size: size))
if let image = CGBitmapContextCreateImage(context) {
return NSImage(CGImage: image, size: size)
}
}
return nil
}
func DrawImageInNSGraphicsContext(size: CGSize, drawFunc: (rect: CGRect) -> Void) -> NSImage? {
guard let rep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(size.width),
pixelsHigh: Int(size.height),
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSCalibratedRGBColorSpace,
bytesPerRow: 0,
bitsPerPixel: 0) else {
return nil
}
let context = NSGraphicsContext(bitmapImageRep: rep)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.setCurrentContext(context)
drawFunc(rect: CGRect(origin: CGPoint.zero, size: size))
NSGraphicsContext.restoreGraphicsState()
let image = NSImage(size: size)
image.addRepresentation(rep)
return image
}
let rect = CGRectMake(0, 0, 100, 20)
let image1 = DrawImageInCGContext(size: rect.size) { context, rect in
CGContextSetFillColorWithColor(context, NSColor.redColor().CGColor)
CGContextFillRect(context, rect);
}
let image2 = DrawImageInNSGraphicsContext(size: rect.size) { rect in
NSColor.blueColor().set()
NSRectFill(rect)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment