Search code examples
ioscgcontextcgimagememory-optimization

Variable size of CGContext


I'm currently using a UIGraphicsBeginImageContext(resultingImageSize); to create an image.

But when I call this function, I don't know exactly the width of resultingImageSize.
Indeed, I developed some kind of video processing which consume lots of memory, and I cannot process first then draw after: I must draw during the video process.

If I set, for example UIGraphicsBeginImageContext(CGSizeMake(300, 400));, the drawn part over 400 is lost.

So is there a solution to set a variable size of CGContext, or resize a CGContext with very few memory consume?


Solution

  • I found a solution by creating a new larger Context each time it must be resized. Here's the magic function:

    void MPResizeContextWithNewSize(CGContextRef *c, CGSize s) {
        size_t bitsPerComponents = CGBitmapContextGetBitsPerComponent(*c);
        size_t numberOfComponents = CGBitmapContextGetBitsPerPixel(*c) / bitsPerComponents;
        CGContextRef newContext = CGBitmapContextCreate(NULL, s.width, s.height, bitsPerComponents, sizeof(UInt8)*s.width*numberOfComponents,
                                                        CGBitmapContextGetColorSpace(*c), CGBitmapContextGetBitmapInfo(*c));
        // Copying context content
        CGImageRef im = CGBitmapContextCreateImage(*c);
        CGContextDrawImage(newContext, CGRectMake(0, 0, CGBitmapContextGetWidth(*c), CGBitmapContextGetHeight(*c)), im);
        CGImageRelease(im);
    
        CGContextRelease(*c);
        *c = newContext;
    }
    

    I wonder if it could be optimized, for example with memcpy, as suggested here. I tried but it makes my code crash.