理解UIGraphicsPushContext(context)和UIGraphicsPopContext()非常令人沮丧的经历
我的理解是,我可以设置上下文的属性,如笔触颜色,然后在堆栈上推送上下文,以便为当前上下文设置新颜色.当我这样做时,我可以通过弹出来返回上下文.
以下是我的代码.当我运行下面的代码时,两行用蓝色绘制.我期望发生的是:我首先将颜色设置为绿色.转到blueLine函数并按下绿色上下文.画蓝色.然后弹出绿色上下文.允许drawLine函数以绿色绘制.
以下是绘制内容的截图(两条蓝线):http://dl.dropbox.com/u/1207310/iOS%20Simulator%20Screen%20shot%20Feb%205%2C%202012%209.00.35%20PM. PNG
任何帮助是极大的赞赏!谢谢.
- (void)drawBlueLine:(CGContextRef)context
{
UIGraphicsPushContext(context);
[[UIColor blueColor] setStroke];
CGContextBeginPath(context);
CGContextMoveToPoint(context, self.bounds.origin.x, 100);
CGContextAddLineToPoint(context, self.bounds.origin.x+self.bounds.size.width, 200);
CGContextStrokePath(context);
UIGraphicsPopContext();
}
- (void)drawLine:(CGContextRef)context
{
UIGraphicsPushContext(context);
CGContextBeginPath(context);
CGContextMoveToPoint(context, self.bounds.origin.x, 200);
CGContextAddLineToPoint(context, self.bounds.origin.x+self.bounds.size.width, 300);
CGContextStrokePath(context);
UIGraphicsPopContext();
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor redColor] setStroke];
CGContextSetLineWidth(context, 5.0);
[self drawBlueLine:context];
[self drawLine:context];
}
Run Code Online (Sandbox Code Playgroud)
或者不应该这样做?
- (void)drawLine:(CGContextRef)oldContext
{
UIGraphicsPushContext(oldContext); //makes oldContext the current context but there is a copy on the stack
[[UIColor blueColor] setStroke];
CGContextBeginPath(oldContext);
CGContextMoveToPoint(oldContext, …Run Code Online (Sandbox Code Playgroud)