可可拉丝错误:"invalid context 0x0"



我想在我的窗口视图上画一些甜蜜的正方形,但我得到一些奇怪的错误。我做错了什么吗?

代码如下:

import Foundation
import AppKit
public class MyWindowView: NSView {
private func drawARectAtPoint(point: NSPoint) {
    let rectToDraw:NSRect = NSMakeRect(point.x, point.y, 200, 200)
    NSColor.blackColor().setStroke()
    var bezier = NSBezierPath(rect: rectToDraw)
    bezier.lineWidth = 2
    bezier.stroke()
}
override public func mouseDown(theEvent: NSEvent) {
    let clickPoint = theEvent.locationInWindow;
    self.drawARectAtPoint(clickPoint)
}
}

我将窗口内容视图的类设置为MyWindowView当我点击它时,我得到如下错误:

Oct 21 14:57:21 ImagineCI[3467]: CGContextSetStrokeColorWithColor: invalid context 0x0。如果您希望看到回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量。Oct 21 14:57:21 ImagineCI[3467]: CGContextSaveGState: invalid context 0x0。如果您希望看到回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量。Oct 21 14:57:21 ImagineCI[3467]: CGContextSetLineCap: invalid context 0x0。如果您想查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量

是的,您需要一个上下文来绘制。最佳实践可能是重写子类的drawRect方法,其中上下文已经自动为您设置,类似于:

import Foundation
import AppKit
public class MyWindowView: NSView {
    private func drawARectAtPoint(point: NSPoint) {
        let rectToDraw:NSRect = NSMakeRect(point.x, point.y, 200, 200)
        NSColor.blackColor().setStroke()
        var bezier = NSBezierPath(rect: rectToDraw)
        bezier.lineWidth = 2
        bezier.stroke()
    }
    private var clickPoint: NSPoint?
    override public func mouseDown(theEvent: NSEvent) {
        clickPoint = theEvent.locationInWindow
        setNeedsDisplayInRect(bounds)
    }
    override public func drawRect(dirtyRect: NSRect) {
        // do all your drawing here
        if let clickPoint = clickPoint {
            drawARectAtPoint(clickPoint)
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新