views:

1537

answers:

1

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.

A: 
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.

Peter Hosey
Where does destinationContext come from? Do I just declare a new one like this: CGContextRef destinationContext;
willc2
The destination context is the one you're going to draw the layer into. Assuming you're not creating the destination context yourself, you'd get it from the context stack by calling `UIGraphicsGetCurrentContext`.
Peter Hosey
Of course, if you plan to make a UIImage instead of draw in a view, you probably will make the context yourself. You'd create a bitmap context, draw into it, then use its buffer to create a CGImage with which to create a UIImage. (There may be an easier way to do this.)
Peter Hosey