我在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)
这有点难看; 如果更新了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的地方打电话.
这似乎正在编译:
var contextPointer = NSGraphicsContext.currentContext()!.graphicsPort()
let context = UnsafePointer<CGContext>(contextPointer).memory
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3591 次 |
| 最近记录: |