views:

49

answers:

2

I have an application that draws images from a CGImage.

The CImage itself is loaded using a CGImageSourceCreateImageAtIndex to create an image from a PNG file.

This forms part of a sprite engine - there are multiple sprite images on a single PNG file, so each sprite has a CGRect defining where it is found on the CGImage.

The problem is, CGContextDraw only takes a destination rect - and stretches the source CGImage to fill it.

So, to draw each sprite image we need to create multiple CGImages from the original source, using CGImageCreateWithImageInRect().

I thought at first that this would be a 'cheap' operation - it doesn't seem necessary for each CGImage to contain its own copy of the images bits - however, profiling has revealed that using CGImageCreateWithImageInRect() is a rather expensive operation.

Is there a more optimal method to draw a sub-section of a CGImage onto a CGContext so I dont need to CGImageCreateWithImageInRect() so often?


Given the lack of a source rectangle, and the ease of making a CGImage from a rect on a CGImage I began to suspect that perhaps CGImage implemented a copy-on-write semantic where a CGImage made from a CGImage would refer to a sub-rect of the same physical bits as the parent. Profiling seems to prove this wrong :/

A: 

Create an NSImage with the CGImage. An NSImage object makes it easy to draw only some section of it to a destination rectangle.

Peter Hosey
it would be ironic if the api i was avoiding as 'inefficient' turned out to bemroe capable and faster.
Chris Becke
CGImage is better for some things, especially reading and writing raster images (with Image I/O). But NSImage is better for some things, too, like resolution-independent drawing (since an NSImage has a size in points to go with its representations' sizes in pixels). There's no single best-at-everything image class on Mac OS X.
Peter Hosey
A: 

I believe the recommendation is to use a clipping region.

Mike Abdullah