Context Managers for CoreGraphics

The CoreGraphics bindings for PyObjC introduce a couple of context manager for use with the with statement. These are simple wrappers around the basic CoreGraphics/Quartz API’s that make using the API more convenient and allow you to write easier to understand code.

Quartz.CGSavedGState(context)

Context manager that wraps a block of code between CGContextSaveGState() and CGContextRestoreGState().

Usage:

with CGSavedGState(context):
   # Change context and use changed context
   pass

# Context is restored to before the with-statement at this point.
Parameters:

context (CGContextRef) – CoreGraphics context value.

Quartz.CGTransparencyLayer(context, info, rect=None)

Context manager that wraps a block of code between CGContextBeginTransparencyLayer() (or CGContextBeginTransparencyLayerWithRect() if rect is not None) and CGContextEndTransparencyLayer().

Usage:

with CGTransparancyLayer(context, None):
    pass

Or:

with CGTransparancyLayer(context, None, myRect):
   pass
Parameters:
  • context (CGContexRef) – A CoreGraphics context.

  • info (dict|None) – A directory with additional information, or None.

  • rect (CGRect) – Bounds for the transparent layer.

Quartz.GContextPage(context, mediaBox=None)

Context manager that wraps a block of code between calls to CGContextBeginPage() and CGContextEndPage()).

Usage:

with CGContextPage(context):
    pass
Parameters:
  • context (CGContextRef) – A CoreGraphics context.

  • mediaBox (CGRect|None) – Optional rectangle defining the bounds of the page. Defaults to the media box for context.