0

I'm having problems getting the subject calls to work. The below test should draw two orange and one green rectangle.

Here is my understanding of the below code...

  • I draw a orange rectangle at 50,50
  • I call the draw greenRect at 200,200, sending the current context
  • I push the current context on the stack, change the stroke color and draw a green rect at 100,100
  • I pop the current context which should restore the original context (orange stroke color)
  • I then draw the last rectangle which should be stroking orange

The last rectangle should stroke orange, but is stroking green, telling me that I modified the original context

Thoughts?

- (void)drawRect:(CGRect)rect{

CGRect aRectangle=CGRectMake(50., 50., 40., 40.);
UIBezierPath *path=[UIBezierPath bezierPathWithRect:aRectangle];
UIColor *strokeColor=[UIColor orangeColor];
[strokeColor setStroke];
[path stroke];

CGContextRef context=UIGraphicsGetCurrentContext();

[self drawGreenRect:context];

CGRect anotherRectangle=CGRectMake(100., 100., 40., 40.);
UIBezierPath *anotherPath=[UIBezierPath bezierPathWithRect:anotherRectangle];
[anotherPath stroke];

}

- (void)drawGreenRect:(CGContextRef)ctxt{

UIGraphicsPushContext(UIGraphicsGetCurrentContext());

CGRect aRectangle=CGRectMake(200., 200., 40., 40.);
UIBezierPath *path=[UIBezierPath bezierPathWithRect:aRectangle];
UIColor *strokeColor=[UIColor greenColor];
[strokeColor setStroke];
[path stroke];

 UIGraphicsPopContext();

}

Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
suhrmesa
  • 11
  • 4

1 Answers1

1

UIGraphicsPushContext() doesn't create a new context for you, it just pushes the context you pass onto a stack. So after you do UIGraphicsPushContext(UIGraphicsGetCurrentContext());, you've got a graphics context stack two deep, but both of the items on it are the same context, the one that was set up by your view for you.

You'll need to actually create a context to push, most likely using UIGraphicsBeginImageContext(). You can then get the image from that context and put it into your view.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • The Apple Docs say UIGraphicsPushContext Makes the specified graphics context the current context. You can use this function to save the previous graphics state and make the specified context the current context. You must balance calls to this function with matching calls to the UIGraphicsPopContext function. You should call this function from the main thread of your application only. How do I use this function to save the graphics context? – suhrmesa Sep 12 '12 at 03:13