Created
July 14, 2015 15:25
-
-
Save randomsequence/b9f4462b005d0ced9a6c to your computer and use it in GitHub Desktop.
Drawing images with CGContext and NSGraphicsContext in Swift
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
//: 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks