我正试图在我的窗口视图上绘制一些甜蜜的方块,但是我得到了一些奇怪的错误。我做错了吗?
以下是代码:
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:无效的上下文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环境变量。
答案 0 :(得分:3)
是的,你需要一个上下文来绘制。最佳做法可能是覆盖子类的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)
}
}
}