willc2
willc2

Reputation: 39671

How to use a CGLayer to draw multiple images offscreen

Ultimately I'm working on a box blur function for use on iPhone.

That function would take a UIImage and draw transparent copies, first to the sides, then take that image and draw transparent copies above and below, returning a nicely blurred image.

Reading the Drawing with Quartz 2D Programming Guide, it recommends using CGLayers for this kind of operation.

The example code in the guide is a little dense for me to understand, so I would like someone to show me a very simple example of taking a UIImage and converting it to a CGLayer that I would then draw copies of and return as a UIImage.

It would be OK if values were hard-coded (for simplicity). This is just for me to wrap my head around, not for production code.

Upvotes: 2

Views: 6215

Answers (1)

Peter Hosey
Peter Hosey

Reputation: 96333

UIImage *myImage = …;
CGLayerRef layer = CGLayerCreateWithContext(destinationContext, myImage.size, /*auxiliaryInfo*/ NULL);
if (layer) {
    CGContextRef layerContext = CGLayerGetContext(layer);
    CGContextDrawImage(layerContext, (CGRect){ CGPointZero, myImage.size }, myImage.CGImage);

    //Use CGContextDrawLayerAtPoint or CGContextDrawLayerInRect as many times as necessary. Whichever function you choose, be sure to pass destinationContext to it—you can't draw the layer into itself!

    CFRelease(layer);
}

That is technically my first ever iPhone code (I only program on the Mac), so beware. I have used CGLayer before, though, and as far as I know, Quartz is no different on the iPhone.

… and return as a UIImage.

I'm not sure how to do this part, having never worked with UIKit.

Upvotes: 2

Related Questions