Understanding UIGraphicsGetCurrentContext()

Crystal picture Crystal · Sep 23, 2011 · Viewed 7.5k times · Source

I'm trying to understand Quartz and getting the context you have to draw on. If I have a function where I create a context, but then I call another function to some other drawing to the same context, do I need to pass the context from the first method to the next? Or can I just use UIGraphicsGetCurrentContext() for any CG methods that require a context since I'm still drawing into the same context?

Answer

davehayden picture davehayden · Dec 5, 2012

The docs for UIGraphicsGetCurrentContext() say:

The current graphics context is nil by default. Prior to calling its drawRect: method, view objects push a valid context onto the stack, making it current. If you are not using a UIView object to do your drawing, however, you must push a valid context onto the stack manually using the UIGraphicsPushContext(_:) function.

So after calling UIGraphicsPushContext() with the context you've created, your other methods can access that context with UIGraphicsGetCurrentContext(). If you're calling UIGraphicsGetCurrentContext() outside of drawRect: and haven't set a context explicitly with UIGraphicsPushContext(), the current graphics context is undefined—and certainly not safe to use.