Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert COpaquePointer in swift to some type (CGContext? in particular)

Tags:

swift

I have the following code in swift which doesn't compile:

class CustomView: NSView {
  override func drawRect(dirtyRect: NSRect) {
    var contextPointer: COpaquePointer = NSGraphicsContext.currentContext()!.graphicsPort()
    var context: CGContext? = contextPointer as? CGContext
    CGContextSetRGBFillColor(context, 1, 0, 0, 1)
    CGContextFillRect(context, CGRectMake(0, 0, 100, 100))
    CGContextFlush(context)
  }
}

How do I convert COpaquePointer to CGContext?

like image 228
Alfa07 Avatar asked Jun 03 '14 07:06

Alfa07


3 Answers

As of Developer Preview 5, NSGraphicsContext now has a CGContext property. It's not documented yet but it's in the header file:

@property (readonly) CGContextRef CGContext NS_RETURNS_INNER_POINTER NS_AVAILABLE_MAC(10_10);
like image 186
robotspacer Avatar answered Nov 09 '22 16:11

robotspacer


This is kind of ugly; it would be better if the graphicsPort() method was updated to return a CGContextRef directly (like UIGraphicsGetCurrentContext()), rather than a void*. I added this extension to NSGraphicsContext to sweep it under the rug for now:

extension NSGraphicsContext {
  var cgcontext: CGContext {
    return Unmanaged<CGContext>.fromOpaque(self.graphicsPort()).takeUnretainedValue()
  }
}

Just call NSGraphicsContext.currentContext().cgcontext anywhere you need a CGContext.

like image 7
jatoben Avatar answered Nov 09 '22 16:11

jatoben


This seems to be compiling:

var contextPointer = NSGraphicsContext.currentContext()!.graphicsPort()
let context = UnsafePointer<CGContext>(contextPointer).memory
like image 3
Alfa07 Avatar answered Nov 09 '22 14:11

Alfa07