【问题标题】:Cocoa Drawing Error: "invalid context 0x0"可可绘图错误:“无效的上下文 0x0”
【发布时间】:2015-10-21 21:15:44
【问题描述】:

我试图在我的窗口视图上绘制一些可爱的方块,但我遇到了一些奇怪的错误。我做错了吗?

代码如下:

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,当我点击它时,我收到如下错误:

10 月 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 环境变量。

【问题讨论】:

    标签: macos swift cocoa drawing nsbezierpath


    【解决方案1】:

    是的,你需要一个上下文来绘制。最佳实践可能是覆盖您的子类的 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)
            }
        }
    }
    

    【讨论】:

    • 不客气!不要忘记接受我的回答,谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 2013-10-30
    • 2012-09-27
    相关资源
    最近更新 更多