问题描述
有两种drawRect方法:
There are two drawRect methods:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
// do drawing here
CGContextRestoreGState(context);
}
和
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(context);
// do drawing here
UIGraphicsPopContext();
}
UIGraphicsPushContext / UIGraphicsPopContext来自 UIKit
而CGContextSaveGState / CGContextRestoreGState来自 CoreGraphics 。
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?
推荐答案
UIGraphicsPushContext(context)
将上下文推送到CGContextRefs堆栈(使上下文成为当前绘图上下文),而 CGContextSaveGState(上下文)
将当前图形状态推送到由上下文维护的图形状态堆栈。如果你需要在当前的绘图上下文中创建一个新的CGContextRef,你应该使用UIGraphicsPushContext,当你使用一个图形上下文并且只想保存时,你应该使用CGContextSaveGState,例如:当前的变换状态,填充或描边颜色,等等。
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.
这篇关于CGContextSaveGState与UIGraphicsPushContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!