Saving + Restoring Graphics Contexts in Core Animationon 24 February 2011

Adding to the previous article about programmatically drawing drop shadows, there was a method used to clear the drop shadow from the graphics context. This is “a” method to clear this drop shadow. What if there were more settings to clear? Settings like clipping, fill and stroke colors, stroke widths, and... there has to be something else... Why not clear everything at the same time, with two lines of code?

The Graphics Context

Obtaining the current graphics context for drawing in a UIView’s drawRect: method is easy. Storing this one in an instance variable is a good idea, as it will be reused for drawing.

CGContextRef ctx = UIGraphicsGetCurrentContext();

The UIView automatically creates the context for drawing. If this was not inside of a UIView we would have to make our own.

Saving + Restoring

There is a blank canvas waiting inside of that graphics context that has been assigned to ctx. Free reign for drawing exists. This is a perfect time to save a copy of this state to the list of graphics contexts. Utilizing the code from the previous post this will be easy.

- (void)drawRect:(CGRect)rect {
  CGContextRef ctx = UIGraphicsGetCurrentContext();
  CGContextSaveGState(ctx);//1. save the “blank canvas”

  CGContextSetShadowWithColor(ctx, CGSizeMake(2.0f, 2.0f), 1.0f, [[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:.6] CGColor]);

  [stringText drawInRect:CGRectMake(0.0, 0.0, 200.0, 40.0) withFont:[UIFont systemFontOfSize:16.0] lineBreakMode:UILineBreakModeClip alignment:UITextAlignmentLeft];
 
  CGContextRestoreGState(ctx);//2. pop my saved blank state
  //Continue drawing
}
 

The code above shows that I get the graphics context and save a “blank canvas” to the list via CGContextSaveGState(ctx) with the context. Drawing then begins by setting up the drop shadow and drawing text. Finally the the original blank canvas state is restored by calling CGContextRestoreGState(ctx). For every save that is called, there must be a corresponding restore method called. No piling up graphics context junk and not removing it when done with it.

Drawing can continue like no drawing had gone before it.

Saving can be used to go back to previous settings as well, not only to a blank state. Depending on where the save is called will determine what is capture in that state at that time.

If you enjoyed this, use this shorter link to share: http://the.ichibod.com/s/sargc