Why do Quartz 2D Graphics Contexts functions have to be called from within the drawRect method?
Because if I call a CGGraphics context function from anywhere except from within drawRect I get messages like this:
<Error>: CGContextFillRects: invalid context
<Error>: CGContextSetFillColorWithColor: invalid context
Actually in a subclass of UIView I do setup a Graphics Context in a method called Render. Bet when Render is called I get the above errors:
- (void)Render {
CGContextRef g = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(g, [UIColor blueColor].CGColor);
CGContextFillRect(g, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height));
CGContextSetFillColorWithColor(g, [UIColor blackColor].CGColor);
[@"It works!" drawAtPoint:CGPointMake(10.0, 20.0) withFont:[UIFont systemFontOfSiz开发者_JS百科e:[UIFont systemFontSize]]];
NSLog(@"gsTest Render");
}
They don't. Maybe you should elaborate a little more.
Cocoa sets up a context for you before calling your drawRect implementation. If you want to draw something somewhere else then that setup work is your responsibility.
UIGraphicsGetCurrentContext retrieves the graphics context from a stack which is set up by the framework. UIKit guarantees that when the drawRect method is called, a valid graphics context has been pushed onto this stack. After you return from it, this stack gets popped. If you call it outside the drawRect function it will not be valid.
Instead, if you want to call it outside drawRect, you need to create/obtain your own graphics context and draw onto that.
Some drawing functions, such as the NSString drawAtPoint:withFont: make use of this stack also; if the current context is not valid you will need to call UIGraphicsPushContext
精彩评论