我在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) } }
如何将COpaquePointer转换为CGContext?
截至开发者预览版5,NSGraphicsContext
现在有一个CGContext
属性.它还没有记录,但它在头文件中:
@property (readonly) CGContextRef CGContext NS_RETURNS_INNER_POINTER NS_AVAILABLE_MAC(10_10);
这有点难看; 如果更新了graphicsPort()方法以直接返回CGContextRef(例如UIGraphicsGetCurrentContext()
),而不是void*,那会更好.我添加了这个扩展名,NSGraphicsContext
以便现在将它扫到地毯下:
extension NSGraphicsContext { var cgcontext: CGContext { return Unmanaged<CGContext>.fromOpaque(self.graphicsPort()).takeUnretainedValue() } }
只需NSGraphicsContext.currentContext().cgcontext
在任何需要CGContext的地方打电话.