问题
调试程序时发现控制台输出了这么一大串错误,核心错误是CGContextXXX: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable。
详细错误如下:
CGContextSetFillColorWithColor: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
CGContextSaveGState: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
CGContextSetFlatness: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
CGContextMoveToPoint: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
CGContextAddCurveToPoint: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
CGContextAddLineToPoint: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
CGContextAddCurveToPoint: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
CGContextAddLineToPoint: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
CGContextAddCurveToPoint: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
CGContextAddLineToPoint: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
CGContextAddCurveToPoint: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
CGContextClosePath: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
CGContextMoveToPoint: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
CGContextDrawPath: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
CGContextRestoreGState: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
...
经过仔细排查后,出现问题的核心代码如下:
...
NSBezierPath* path = [NSBezierPath bezierPathWithRoundedRect:frame xRadius:radius yRadius:radius];
path.lineWidth = lineWidth;
path.flatness = 0.0;
//这里出现问题
[fillColor setFill];
[path fill];
...
错误原因
个人理解,控制台打印错误的含义为:当前绘图的上下文为空,因此无法绘制。即就是说:只有在drawRect函数内部才提供了绘制图形上下文环境,不能在非drawRect函数内部通过NSBezierPath或者CGPathRef绘制内容。(个人经验所得,若有谬误,请及时指出。)
解决方案
把所有与NSBezierPath或者CGPathRef绘图相关的代码移至drawRect函数内。
(以上错误也暴露出,NSBezierPath的fill方法内部的具体实现原理。)
网友评论