CGContextSaveGState vs UIGraphicsPushContext

隐身守侯 提交于 2019-11-29 16:51:03

问题


There are two drawRect methods:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    // do drawing here
    CGContextRestoreGState(context);
}

And

- (void)drawRect:(CGRect)rect 
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIGraphicsPushContext(context);
    // do drawing here
    UIGraphicsPopContext(); 
}

UIGraphicsPushContext / UIGraphicsPopContext are from UIKit while CGContextSaveGState / CGContextRestoreGState are from CoreGraphics.

Questions: What is the difference between those methods? Which one is better to use? Are there some examples of proving one method better than other and vise versa?


回答1:


UIGraphicsPushContext(context) pushes context onto a stack of CGContextRefs (making context the current drawing context), whereas CGContextSaveGState(context) pushes the current graphics state onto the stack of graphics states maintained by context. You should use UIGraphicsPushContext if you need to make a new CGContextRef the current drawing context, and you should use CGContextSaveGState when you're working with one graphics context and just want to save, for example: the current transform state, fill or stroke colors, etc.




回答2:


UIGraphicsPushContext(ctx) is useful when you want to draw with UIkit and the current context is not the context which you want to draw in.You use this function to make the context which you want to draw in become current context. CGContextSaveGState(ctx) save context (referred by ctx),later you can restore the context use CGContextRestoreGState()



来源:https://stackoverflow.com/questions/15505871/cgcontextsavegstate-vs-uigraphicspushcontext

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