Cocoa Drawing Error: "invalid context 0x0"

Cocoa Drawing Error: "invalid context 0x0"

我正试图在我的 window 视图上绘制一些漂亮的方块,但出现了一些奇怪的错误。我做错了什么吗?

代码如下:

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)
}
}

我将 window 内容视图的 class 设置为 MyWindowView,当我点击它时,出现如下错误:

10 月 21 日 14:57:21ImagineCI[3467]:CGContextSetStrokeColorWithColor:无效上下文 0x0。如果要查看回溯,请设置 CG_CONTEXT_SHOW_BACKTRACE 环境变量。 10 月 21 日 14:57:21 ImagineCI[3467]:CGContextSaveGState:无效上下文 0x0。如果要查看回溯,请设置 CG_CONTEXT_SHOW_BACKTRACE 环境变量。 10 月 21 日 14:57:21 ImagineCI[3467]:CGContextSetLineCap:无效上下文 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)
        }
    }
}