Skip to content

Instantly share code, notes, and snippets.

@randomsequence
Created July 14, 2015 15:25
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save randomsequence/b9f4462b005d0ced9a6c to your computer and use it in GitHub Desktop.
Save randomsequence/b9f4462b005d0ced9a6c 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) -> ()) -> NSImage {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(
nil,
Int(size.width),
Int(size.height),
8,
0,
colorSpace,
bitmapInfo)
drawFunc(context: context)
let image = CGBitmapContextCreateImage(context)
return NSImage(CGImage: image, size: size)
}
func DrawImageInNSGraphicsContext(#size: CGSize, #drawFunc: ()->()) -> NSImage {
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)
let context = NSGraphicsContext(bitmapImageRep: rep!)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.setCurrentContext(context)
drawFunc()
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) -> () in
CGContextSetFillColorWithColor(context, NSColor.redColor().CGColor)
CGContextFillRect(context, rect);
}
let image2 = DrawImageInNSGraphicsContext(size: rect.size) { () -> () in
NSColor.blueColor().set()
NSRectFill(rect)
}
@seadiem
Copy link

seadiem commented May 25, 2018

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment