drawRect context Error
I heard that a lot of people get a context error by not using drawRect
Now I have this:
- (void)drawRect:(CGRect)rect {
NSLog(@"drawRect: Starts");
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextSetLineWidth(context, 3.0);
CGContextMoveToPoint(context, lineStart.x, lineStart.y);
CGContextAddLineToPoint(context, lineEnd.x, lineEnd.y);
CGContextStrokePath(context);
}
Error:
<Error>: CGContextSetRGBStrokeColor: invalid context
Which had work on previous programs, but not on this one. Whats different: I have a view controller, which calls thi开发者_如何学Gos UIView:
-(void)createLine:(CGPoint)start:(CGPoint)end {
NSLog(@"createLine: Starts");
lineEnd = start;
lineStart = end;
self = [super initWithFrame:drawRect:CGRectMake(fmin(lineStart.x, lineEnd.x), fmin(lineStart.y, lineEnd.y), fabs(lineStart.x - lineEnd.x), fabs(lineStart.y - lineEnd.y))];
}
This is my first question, and I am not sure how much info code I should be putting here so be easy on me.
At the risk of stating the obvious, it looks like you're calling createLine
sometime when you don't have a valid context. This is why it's not a good idea to call drawRect
directly. Intsead, call setNeedsDisplay
and let the system call drawRect
at a suitable time.
As walkytalky wrote, you should not call drawRect
directly. If you need to make sure that a call to drawRect
is triggered, then call setNeedsDisplay
, which will make sure that drawRect
is called at the appropriate time.
The last line of your createLine::
method is a bit confusing and unorthodox. I think that for your purposes that you want to delete that line and simply replace it with a all to setNeedsDisplay
. That should trigger a call to drawRect
with the new lineStart and lineEnd values.
精彩评论