Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing UIGraphicsPushContext(context) and UIGraphicsPopContext()
    text
    copied!<p>Very frustrating experience understanding UIGraphicsPushContext(context) and UIGraphicsPopContext()</p> <p>My understanding is that I can set attributes of the context like the stroke color and then push the context on a stack so I can set a new color for the current context. When I'm done doing that I can return to the context by popping it.</p> <p>Below is my code. When I run the code below two lines are drawn in blue. What I expect to happen is: that I first set the color green. Go to the blueLine function and push the green context. Draw in blue. Then pop the green context. Allowing the drawLine function to drawn in green. </p> <p>Here is a screenshot of what is drawn (two blue lines): <a href="http://dl.dropbox.com/u/1207310/iOS%20Simulator%20Screen%20shot%20Feb%205,%202012%209.00.35%20PM.png" rel="nofollow">http://dl.dropbox.com/u/1207310/iOS%20Simulator%20Screen%20shot%20Feb%205%2C%202012%209.00.35%20PM.png</a></p> <p>Any help is GREATLY appreciated! Thank you.</p> <pre><code>- (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]; } </code></pre> <p>Or shouldn't this work?</p> <pre><code>- (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?` </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload