title: How to create a CGLayer from a UIView for off-screen drawing
body: <p>I have read what I believe to be the relevant parts of the Quartz 2D Programming Guide, but cannot find an answer to the following (they don't seem to talk a lot about iOS in the document):</p>
  
  <p>My application displays a drawing in a <code>UIView</code>. Every now and then I have to update the drawing in some way, e.g. change the fill colour of one of the shapes (I keep <code>CGPathRefs</code> to the important shapes to be able to redraw them with a different fill colour later). As described in the Section "Drawing With a CGLayer" on page 169 of the aforementioned document, I was thinking of drawing the entire drawing into a <code>CGContext</code> that I would obtain from a <code>CGLayer</code>, like so:</p>
  
  <pre><code>CGContextRef offscreenContext = CGLayerGetContext(offscreenLayer);
  </code></pre>
  
  <p>Then I could do my updating off-screen into the <code>CGContext</code> and draw the <code>CGLayer</code> into my UIView in the <code>UIView</code>'s drawRect: method, like so:</p>
  
  <pre><code>CGContextDrawLayerAtPoint(viewContext, CGPointZero, offscreenLayer);
  </code></pre>
  
  <p>The problem I am having is, where do I get my <code>CGLayer</code> from? My understanding is I have to make it using <code>CGLayerCreateWithContext</code> and supply a <code>CGContext</code> as a parameter from which it inherits most of it's properties. Obviously, the right context would be the context of the <code>UIView</code>, that I am getting with </p>
  
  <pre><code>CGContextRef viewContext = UIGraphicsGetCurrentContext();
  </code></pre>
  
  <p>but if I am not mistaken, I can only get that within the <code>drawRect</code>: method and it is not valid to assume that the context I am given there will be the same one next time the method is called, i.e. I can only use that <code>CGContext</code> locally within the method.</p>
  
  <p>So, how can I get a <code>CGContext</code> that I can use to initialise my <code>CGLayer</code> to create an offscreen <code>CGContext</code> to draw into and then draw the entire layer back into my <code>UIView</code>'s <code>CGContext</code>?</p>
  
  <p>PS: While you're at it; if anything above does not make sense or is not sane, please let me know. I am just starting to get my head around Quartz 2D.</p>