‘invalid context 0x0’ error when using CGContext*

2019-01-15 15:42发布

问题:

/*  Adding the Path */
UserGraphBuff = UIGraphicsGetCurrentContext();

CGContextSetRGBStrokeColor(UserGraphBuff,5,10,0,1);
CGContextSetLineWidth(UserGraphBuff, 2 );

CGContextBeginPath(UserGraphBuff);  

//line to last user point
CGContextAddLineToPoint(UserGraphBuff, (*xVal)[sizeof xVal / sizeof *xVal - 1], (*yNewVal)[sizeof yNewVal / sizeof *yNewVal - 1]);
//line to rest of user points in reverse order
for (int i = sizeof xVal / sizeof *xVal - 1; i > -1; i--){
    CGContextAddLineToPoint(UserGraphBuff, (*xVal)[i], (*yNewVal)[i]);
}

//EOFill
CGContextEOFillPath(UserGraphBuff);

Above is the code I am trying to work through. Its supposed to do what CGContext says it does but I am not getting any thing drawn. I keep getting this error:

Fri Oct 28 13:18:40 case.app testApplication[4127] <Error>: CGContextSetRGBStrokeColor: invalid context 0x0
Fri Oct 28 13:18:40 case.app testApplication[4127] <Error>: CGContextSetLineWidth: invalid context 0x0
Fri Oct 28 13:18:40 case.app testApplication[4127] <Error>: CGContextBeginPath: invalid context 0x0
Fri Oct 28 13:18:40 case.app testApplication[4127] <Error>: CGContextAddLineToPoint: invalid context 0x0
Fri Oct 28 13:18:40 case.app testApplication[4127] <Error>: CGContextDrawPath: invalid context 0x0

I reference the CGContextRef in my header file.

i don't think i understand CGContext well enough nor do i know what CGContextRef should be.

回答1:

For your code to work, it needs to be executed in the drawRect method of your UIView subclass (and you don't call drawRect directly - this is called by the OS when it needs the UIView to render itself). You're presumably trying to run this code from a touch event or from viewDidLoad or something like that.