我正在将NSView移植到Swift,我需要使用Quartz CGContextAddPath.
import Cocoa
class MYView: NSView {
init(frame: NSRect) {
super.init(frame: frame)
}
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
NSColor .redColor() .set()
NSRectFill(self.bounds)
var p :CGMutablePathRef = CGPathCreateMutable()
var ctx = NSGraphicsContext.currentContext().graphicsPort()
CGContextAddPath(ctx, p) // compiler rejects this line
}
}
Run Code Online (Sandbox Code Playgroud)
你怎么理解这个错误信息?
Cannot convert the expression's type 'Void' to type 'CGContext!'
Run Code Online (Sandbox Code Playgroud)
CGContextAddPath的Swift签名是:
func CGContextAddPath(context: CGContext!, path: CGPath!)
Run Code Online (Sandbox Code Playgroud)
我的错误是什么?
我用这个时:
let context = UnsafePointer<CGContext>(ctx).memory
Run Code Online (Sandbox Code Playgroud)
我现在有一个运行时错误:
Jun 3 15:57:13 xxx.x SwiftTest[57092] <Error>: CGContextAddPath: invalid context 0x7fff73bd0060. This is a serious error. …
我正在尝试将此objc代码转换为swift:
CGContextRef contextRef = CGBitmapContextCreate(NULL,
proposedRect.size.width,
proposedRect.size.height,
CGImageGetBitsPerComponent(imageRef),
0,
colorSpaceRef,
(CGBitmapInfo)kCGImageAlphaPremultipliedFirst);
NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:contextRef flipped:NO];
Run Code Online (Sandbox Code Playgroud)
到目前为止,我最终得到了这个:
var bitmapContext: CGContext = CGBitmapContextCreate(data, UInt(proposedRect.width), UInt(proposedRect.height), CGImageGetBitsPerComponent(image), 0, colorSpace, CGBitmapInfo(CGImageAlphaInfo.PremultipliedFirst.toRaw()))
let context = NSGraphicsContext(graphicsPort: bitmapContext, flipped: false)
Run Code Online (Sandbox Code Playgroud)
问题是,CGBitmapContextCreate收益CGContext类型和NSGraphicsContext初始化参数graphicsPort的CMutableVoidPointer类型.那我怎么转换CGContext成CMutableVoidPointer?
相关的反向类型转换在这里找到,但它没有提供太多帮助 如何将swpa中的COpaquePointer转换为某种类型(特别是CGContext?)