CoreGraphics将结果绘制到CGContextDrawPath:无效的上下文0x0

时间:2016-11-07 19:39:07

标签: ios swift sprite-kit core-graphics

我从此代码中收到了大量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)
                            }

                        }
                    }

1 个答案:

答案 0 :(得分:1)

查看您的代码,我相信罪魁祸首的代码行是:

circlePath.fill()

由于UIBezierPath.fill()是一个核心图形绘制操作,需要在核心图形上下文中调用它,以便它知道它实际绘制的位置。

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

从它的外观来看,在代码的那一部分中调用fill()是在存在的上下文之外进行的,这就是为什么它报告了一个无效的0x0上下文。

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

如果您需要进一步说明,请与我们联系。 :)

相关问题