Quartz 2D Graphics Contexts

不羁岁月 提交于 2019-12-08 11:54:17

问题


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 systemFontOfSize:[UIFont systemFontSize]]];
    NSLog(@"gsTest Render");
}

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/1925123/quartz-2d-graphics-contexts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!