Advertisement
Guest User

Untitled

a guest
Nov 29th, 2015
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. //: Playground - noun: a place where people can play
  2.  
  3. import Cocoa
  4.  
  5. let bounds = CGRectMake(0, 0, 100, 100);
  6.  
  7. func DrawImageInCGContext(size: CGSize, drawFunc: (context: CGContextRef, rect: CGRect) -> Void) -> NSImage? {
  8. let colorSpace = CGColorSpaceCreateDeviceRGB()
  9. let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
  10. if let context = CGBitmapContextCreate(
  11. nil,
  12. Int(size.width),
  13. Int(size.height),
  14. 8,
  15. 0,
  16. colorSpace,
  17. bitmapInfo.rawValue) {
  18. drawFunc(context: context, rect: CGRect(origin: CGPoint.zero, size: size))
  19. if let image = CGBitmapContextCreateImage(context) {
  20. return NSImage(CGImage: image, size: size)
  21. }
  22.  
  23. }
  24. return nil
  25. }
  26.  
  27. func DrawImageInNSGraphicsContext(size: CGSize, drawFunc: (rect: CGRect) -> Void) -> NSImage {
  28. let rep = NSBitmapImageRep(
  29. bitmapDataPlanes: nil,
  30. pixelsWide: Int(size.width),
  31. pixelsHigh: Int(size.height),
  32. bitsPerSample: 8,
  33. samplesPerPixel: 4,
  34. hasAlpha: true,
  35. isPlanar: false,
  36. colorSpaceName: NSCalibratedRGBColorSpace,
  37. bytesPerRow: 0,
  38. bitsPerPixel: 0)
  39.  
  40. let context = NSGraphicsContext(bitmapImageRep: rep!)
  41.  
  42. NSGraphicsContext.saveGraphicsState()
  43. NSGraphicsContext.setCurrentContext(context)
  44.  
  45. drawFunc(rect: CGRect(origin: CGPoint.zero, size: size))
  46.  
  47. NSGraphicsContext.restoreGraphicsState()
  48.  
  49. let image = NSImage(size: size)
  50. image.addRepresentation(rep!)
  51.  
  52. return image
  53. }
  54.  
  55. let rect = CGRectMake(0, 0, 100, 20)
  56.  
  57. let image1 = DrawImageInCGContext(size: rect.size) { (context) -> () in
  58. CGContextSetFillColorWithColor(context, NSColor.redColor().CGColor)
  59. CGContextFillRect(context, rect);
  60. }
  61.  
  62. let image2 = DrawImageInNSGraphicsContext(size: rect.size) { () -> () in
  63. NSColor.blueColor().set()
  64. NSRectFill(rect)
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement