加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 如何使用Implicitly Unwrapped Optionals?

发布时间:2020-12-14 02:26:42 所属栏目:百科 来源:网络整理
导读:我正在将NSView移植到 Swift,我需要使用Quartz CGContextAddPath. import Cocoaclass MYView: NSView { init(frame: NSRect) { super.init(frame: frame) } override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) NSColor .redColor() .se
我正在将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

    }

}

你怎么理解这个错误信息?

Cannot convert the expression's type 'Void' to type 'CGContext!'

CGContextAddPath的Swift签名是:

func CGContextAddPath(context: CGContext!,path: CGPath!)

我的错误是什么?

我用这个时:

let context = UnsafePointer<CGContext>(ctx).memory

我现在有一个运行时错误:

Jun 3 15:57:13 xxx.x SwiftTest [57092]<错误>:CGContextAddPath:无效的上下文0x7fff73bd0060.这是一个严重的错误.该应用程序或其使用的库正在使用无效的上下文,从而导致系统稳定性和可靠性的整体降低.此通知是礼貌的:请解决此问题.它将成为即将到来的更新中的致命错误.

这是我目前使用的代码:

import Cocoa

class MYView: NSView {

    init(frame: NSRect) {
        super.init(frame: frame)
    }

    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)

        var p :CGMutablePathRef =  CGPathCreateMutableCopy( CGPathCreateWithRoundedRect(self.bounds,10,nil))
        var ctx =  NSGraphicsContext.currentContext().graphicsPort()
        let context = UnsafePointer<CGContext>(ctx).memory

        CGContextAddPath(context,p) // compiler no longer rejects this line
        var blueColor = NSColor.blueColor()
        CGContextSetStrokeColorWithColor(context,NSColor.blueColor().CGColor)
        CGContextSetLineWidth(context,2)
        CGContextStrokePath(context)

    }

}
截至Swift 1.0

如果您的部署目标是10.10,则可以使用Yosemite引入的便捷方法.

let context = NSGraphicsContext.currentContext().CGContext

如果你必须支持10.9,你必须按照下面的方法手动转换上下文.

let contextPtr = NSGraphicsContext.currentContext().graphicsPort
let context = unsafeBitCast(contextPtr,CGContext.self)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读