myc*_*elo 3 iphone uicolor ios
理解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, self.bounds.origin.x, 200);
CGContextAddLineToPoint(oldContext, self.bounds.origin.x+self.bounds.size.width, 300);
CGContextStrokePath(oldContext);
UIGraphicsPopContext(); //previous oldContext is moved back into place containing red?
}
- (void)drawRect:(CGRect)rect
{
CGContextRef oldContext = UIGraphicsGetCurrentContext();
[[UIColor redColor] setStroke];
[self drawLine:oldContext];
//anything I draw here should be red. Shouldn't it?`
Run Code Online (Sandbox Code Playgroud)
什么UIGraphicsPushContext和UIGraphicsPopContext做什么改变用于绘制的上下文,不一定保存和恢复任何给定的上下文的状态.你的代码正在做的只是重复地用你抓到的上下文替换调用前的当前drawRect:上下文UIGraphicsGetCurrentContext(它们可能是相同的).
如果要保存还原给定上下文的状态,请使用CGContextSaveGState而CGContextRestoreGState不是.
| 归档时间: |
|
| 查看次数: |
4794 次 |
| 最近记录: |