【问题标题】:CoreGraphics drawing results to CGContextDrawPath: invalid context 0x0CoreGraphics 绘制结果到 CGContextDrawPath:无效上下文 0x0
【发布时间】:2016-11-07 19:39:06
【问题描述】:

我从这段代码中得到了大量的CGContextDrawPath: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable. 错误。它在 SKScene 中执行。基本上,我将用户的绘图作为 SKShapeNode 显示在屏幕上。然后我用 Core Graphics 的圆圈填充该绘图的路径。然而,代码运行缓慢,给了我很多错误。我对 Swift 有点陌生。你能帮我看看发生了什么事吗?我怎样才能加快速度?如何为 CoreGraphics 提供适当的上下文?

                    let boundingBox = createdShape.frame
                    for j in stride(from: Int(boundingBox.minX), to: Int(boundingBox.maxX), by: 10) {
                        for i in stride(from: Int(boundingBox.minY), to: Int(boundingBox.maxY), by: 10) {
                        //for i in 0..<10 {
                            counter += 1
                            //let originalPoint = CGPoint(x: ((boundingBox.maxX - boundingBox.minX)/2)+boundingBox.minX, y: (boundingBox.maxY-CGFloat(i*10)))
                            //let originalPoint = CGPoint(x: CGFloat(j), y: (boundingBox.maxY-CGFloat(i*10)))
                            let originalPoint = CGPoint(x: CGFloat(j), y: (CGFloat(i)))
                            let point:CGPoint = self.view!.convert(originalPoint, from: self)

                            if (createdShape.path?.contains(createdShape.convert(originalPoint, from: self)))! {
                                let circlePath = UIBezierPath(arcCenter: point, radius: CGFloat(5), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
                                circlePath.fill()

                                let shapeLayer = CAShapeLayer()
                                shapeLayer.path = circlePath.cgPath

                                shapeLayer.fillColor = UIColor(red:  180/255, green: 180/255, blue: 180/255, alpha: 0.4).cgColor
                                shapeLayer.strokeColor = UIColor(red:  180/255, green: 180/255, blue: 180/255, alpha: 0.4).cgColor
                                shapeLayer.lineWidth = 0.0

                                view!.layer.addSublayer(shapeLayer)
                            }

                        }
                    }

【问题讨论】:

  • 好吧,看起来你在这里混合了 2 种不同的技术,你让自己感到困惑。您不想处理核心图形,

标签: ios swift sprite-kit core-graphics


【解决方案1】:

查看您的代码,我认为罪魁祸首是:

circlePath.fill()

由于UIBezierPath.fill() 是一个Core Graphics 绘制操作,它需要在Core Graphics 上下文中调用才能知道它实际绘制的位置。

这通常在 UIGraphicsBeginImageContextWithOptions() / UIGraphicsEndImageContext() 内完成,您可以在其中显式创建和结束上下文,或者在某些 UIKit 方法(如 UIView.drawRect())中自动为您管理上下文。

从外观上看,在代码的那部分调用 fill() 是在存在的上下文之外完成的,这就是它报告 0x0 的无效上下文的原因。

在这种特殊情况下,您似乎正在使用 circlePath 对象作为 CAShapeLayer 的剪贴蒙版,因此可能没有必要在此处调用 fill()

如果您需要进一步说明,请告诉我。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多