Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy CGContext into another CGContext

I am performing some CG drawing operations into a CGContext that I created for an MKMapOverlayView. After drawing into my context, I create an image and paste it into the context that MapKit provided.

- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context {
    CGColorSpaceRef colorRef = CGColorSpaceCreateDeviceRGB();
    CGContextRef myContext = CGBitmapContextCreate(NULL, kTileSize, kTileSize, 8, 0, colorRef, kCGImageAlphaPremultipliedLast);
    CGColorSpaceRelease(colorRef);
    CGContextSetAllowsAntialiasing(myContext, TRUE);
    //...cut out drawing operations...
    CGImageRef image = CGBitmapContextCreateImage(myContext);
    CGContextDrawImage(context, [self rectForMapRect:mapRect], image);
    CGImageRelease(image);
    CGContextRelease(myContext);
}

Is there a way to simply copy myContext into context without having to create an image?

I realize that some of you will say "why not just draw directly into the context that MapKit provides". Unfortunately, we're experiencing a drawing glitch when rendering into context directly. Apple is currently investigating this issue for us, but in the meantime we need to get a workaround in place. This workaround I presented above is my "best" shot, but it is a bit on the slow side.

P.S. I have started a bounty since I'm looking for an answer here too. Specifically I'm targeting OS X. So the answer should work there. The OP was looking for an answer on iOS.

like image 596
Tim Reddy Avatar asked Aug 05 '11 15:08

Tim Reddy


1 Answers

You could use a CGLayerRef. The layer ref is like sub-context that you do a bunch of drawing into, and then flatten down into the original context when you finish drawing the layer's worth of content.

It's typically used to get shared alpha or shadows across many drawing calls rather than each individual call.

I don't know if this will still workaround whatever bug you're encountering, or whether the performance is better or worse than the two context approach. I'd need to know more about your goals and requirements. For example, do you you want to avoid using two context to avoid a second copy, or because you don't want to pay the memory for the second image?

like image 152
Jon Hess Avatar answered Sep 22 '22 18:09

Jon Hess