Since CGContextDrawImage can be quite expensive, I’m trying to minimize the amount of data I’m giving it while I examine the pixel data. If I have two images and the CGRect of their intersection, can I get CGContextDrawImage to only draw the intersection of each independently (resulting in two CGContextRefs containing the intersection of one of the images)?
Here’s some code that doesn’t work, but should be close to what I need for one image…
CGImageRef imageRef = [image CGImage];
NSUInteger width = rectIntersect.size.width;
NSUInteger height = rectIntersect.size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
// rectIntersect down here contains the intersection of the two images...
CGContextDrawImage(context, rectIntersect, imageRef);
Well, you don’t need to draw them unless you really want a
CGBitmapContextwith them. UseCGImageCreateWithImageInRect()to create sub-images. This doesn’t necessarily require the frameworks to copy any image data. It may just reference the image data from the original. So, it can be quite efficient.If you really do need the images drawn into contexts, you can of course just draw the sub-images.