CGContextSaveGState与UIGraphicsPushContext

Vad*_*dim 24 objective-c cgcontext drawrect ios

有两种drawRect方法:

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

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

UIGraphicsPushContext/UIGraphicsPopContext来自UIKit, 而CGContextSaveGState/CGContextRestoreGState来自CoreGraphics.

问题:这些方法有什么区别?哪一个更好用?是否有一些证明一种方法比其他方法更好的例子,反之亦然?

Aar*_*den 36

UIGraphicsPushContext(context)将上下文推送到CGContextRefs堆栈(使上下文成为当前绘图上下文),而CGContextSaveGState(context)将当前图形状态推送到上下文维护的图形状态堆栈上.如果你需要在当前的绘图上下文中创建一个新的CGContextRef,你应该使用UIGraphicsPushContext,当你使用一个图形上下文并且只想保存时,你应该使用CGContextSaveGState,例如:当前的变换状态,填充或描边颜色,等等