我试图使用鼠标事件在视图上绘制,但是xcode给出了"无效的上下文"。有谁能告诉我我做错了什么吗?
class DrawingView: NSView {
var gContext:CGContextRef?
var lastPoint = NSPoint(x:0, y:0)
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var brushWidth: CGFloat = 10.0
var opacity: CGFloat = 1.0
var swiped = false
func drawLineFrom(p1:NSPoint, p2:NSPoint){
// CGContextBeginPath(gContext)
// CGContextSetRGBStrokeColor(gContext, 0, 0, 0, 1)
NSColor.redColor().set() // choose color
CGContextSetLineWidth(gContext, 10.0)
CGContextMoveToPoint(gContext, p1.x, p1.y)
CGContextAddLineToPoint(gContext, p2.x, p2.y)
CGContextStrokePath(gContext)
// self.setNeedsDisplayInRect(self.bounds)
needsDisplay = true
}
override func mouseUp(theEvent: NSEvent) {
swiped = true
let droppings = theEvent.locationInWindow
let currentPoint:NSPoint = self.convertPoint(droppings, fromView: nil)
self.drawLineFrom(lastPoint, p2: currentPoint)
Swift.print("Up \(currentPoint)")
lastPoint = currentPoint
}
override func mouseDown(theEvent: NSEvent) {
// let position = theEvent.locationInWindow
// Swift.print("Mouse Down: \(position.x) - \(position.y)")
if theEvent.clickCount == 1{
let point:NSPoint = self.convertPoint(theEvent.locationInWindow, fromView: self)
Swift.print("Point >> \(point)")
lastPoint = point
}
}
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
// Drawing code here.
let context = NSGraphicsContext.currentContext()?.CGContext
let rawContext = NSGraphicsContext.currentContext()
rawContext?.saveGraphicsState()
self.gContext = context
CGContextSetRGBStrokeColor(context, 0, 0, 0, 1)
CGContextSetLineWidth(context, 10.0)
CGContextMoveToPoint(context, 0, 0)
CGContextAddLineToPoint(context, 200, 200)
CGContextStrokePath(context)
}
以下是我的调试输出...
点 >> (247.71484375, 108.34375) Oct 25 15:40:07 OSX Basics[17113] : CGContextSetFillColorWithColor: 无效的上下文0x0。如果您想查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量。 Oct 25 15:40:07 OSX Basics[17113] : CGContextSetStrokeColorWithColor: 无效的上下文0x0。如果您想查看回溯,请设置CG_CONTEXT_SHOW_BACKTRACE环境变量。 向上 (394.96484375, 220.5078125)