iOS " current graphics context" - What is that

Ian Vink picture Ian Vink · Jan 23, 2011 · Viewed 9.3k times · Source

When I draw lines and shapes etc I get the " current graphics context" in iOS.

What exactly though is " current graphics context" - I'm looking for the 30,000 foot description.

Right now I just copy and paste UI code, not exactly sure what it's doing.

Answer

Lily Ballard picture Lily Ballard · Jan 23, 2011

A graphics context is the place where information about the drawing state is stored. This includes fill color, stroke color, line width, line pattern, winding rule, mask, current path, transparency layers, transform, text transform, etc. When using CoreGraphics calls, you specify the context to use to every single function. This means you can use multiple contexts at once, though typically you only use one. At the UIKit layer, there is the concept of a "current" graphics context, which is a graphics context that's used by all UIKit-level drawing calls (such as -[UIColor set] or UIBezierPath drawing). The current context is stored in a stack of contexts, so you can create a new context for some drawing, then when you finish with it the previous context is restored. Typically you get a context for free inside of -[UIView drawRect:] inside of CALayer display-related methods, but not otherwise.

It used to be that the "current" context was an application-wide global state, and therefore was not safe to touch outside of the main thread. As of iOS 4.0 (I believe), this became a thread-local state and UIKit-level drawing methods became safe to use on background threads.