如何在swift中将COpaquePointer转换为某种类型(特别是CGContext?)

Alf*_*a07 8 swift

我在swift中有以下代码,不能编译:

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

如何将COpaquePointer转换为CGContext?

rob*_*cer 10

截至开发者预览版5,NSGraphicsContext现在有一个CGContext属性.它还没有记录,但它在头文件中:

@property (readonly) CGContextRef CGContext NS_RETURNS_INNER_POINTER NS_AVAILABLE_MAC(10_10);
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,这仅适用于10.10. (3认同)

jat*_*ben 7

这有点难看; 如果更新了graphicsPort()方法以直接返回CGContextRef(例如UIGraphicsGetCurrentContext()),而不是void*,那会更好.我添加了这个扩展名,NSGraphicsContext以便现在将它扫到地毯下:

extension NSGraphicsContext {
  var cgcontext: CGContext {
    return Unmanaged<CGContext>.fromOpaque(self.graphicsPort()).takeUnretainedValue()
  }
}
Run Code Online (Sandbox Code Playgroud)

只需NSGraphicsContext.currentContext().cgcontext在任何需要CGContext的地方打电话.

  • 这不再适用于Xcode6/DP3 :( (2认同)

Alf*_*a07 3

这似乎正在编译:

var contextPointer = NSGraphicsContext.currentContext()!.graphicsPort()
let context = UnsafePointer<CGContext>(contextPointer).memory
Run Code Online (Sandbox Code Playgroud)