Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //: 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 {
- 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(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) -> () in
- CGContextSetFillColorWithColor(context, NSColor.redColor().CGColor)
- CGContextFillRect(context, rect);
- }
- let image2 = DrawImageInNSGraphicsContext(size: rect.size) { () -> () in
- NSColor.blueColor().set()
- NSRectFill(rect)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement