title: iOS - is it possible to cache CGContextDrawImage?
body: <p>I used the timing profile tool to identify that 95% of the time is spent calling the function CGContextDrawImage. </p>
  
  <p>In my app there are a lot of duplicate images repeatably being chopped from a sprite map and drawn to the screen. I was wondering if it was possible to cache the output of CGContextDrawImage in an NSMutableDictionay, then if the same sprite is requested again it can be just pull it from the cache rather than doing all the work of clipping and rendering it again. This is what i’ve got but I have not been to successful:</p>
  
  <p><strong>Definitions</strong></p>
  
  <pre><code>if(cache == NULL) cache = [[NSMutableDictionary alloc]init];
  //Identifier based on the name of the sprite and location within the sprite.
  NSString* identifier = [NSString stringWithFormat:@"%@-%d",filename,frame];
  </code></pre>
  
  <p><strong>Adding to cache</strong></p>
  
  <pre><code> CGRect clippedRect = CGRectMake(0, 0, clipRect.size.width, clipRect.size.height);
      CGContextClipToRect( context, clippedRect);
  
      //create a rect equivalent to the full size of the image
      //offset the rect by the X and Y we want to start the crop
      //from in order to cut off anything before them
      CGRect drawRect = CGRectMake(clipRect.origin.x * -1,
                                   clipRect.origin.y * -1,
                                   atlas.size.width,
                                   atlas.size.height);
  
      //draw the image to our clipped context using our offset rect
      CGContextDrawImage(context, drawRect, atlas.CGImage);
      [cache setValue:UIGraphicsGetImageFromCurrentImageContext() forKey:identifier];
      UIGraphicsEndImageContext();
  </code></pre>
  
  <p><strong>Rendering a cached sprite</strong>
  There is probably a better way to render CGImage which is my ultimate caching goal but at the moment I’m just looking to successfully render the cached image out however this has not been successful. </p>
  
  <pre><code> UIImage* cachedImage = [cache objectForKey:identifier];
  
  if(cachedImage){
      NSLog(@"Cached %@",identifier);
  
      CGRect imageRect =  CGRectMake(0,
                                     0,
                                     cachedImage.size.width,
                                     cachedImage.size.height);
  
      if (NULL != UIGraphicsBeginImageContextWithOptions)
          UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, 0);
      else
          UIGraphicsBeginImageContext(imageRect.size);
  
      //Use draw for now just to see if the image renders out ok
      CGContextDrawImage(context, imageRect, cachedImage.CGImage);
       UIGraphicsEndImageContext();
  }
  </code></pre>