Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGContextDrawPDFPage taking up large amounts of memory

I have a PDF file that I want to draw in outline form. I want to draw the first several pages on the document each in their own UIImage to use on a button so that when clicked, the main display will navigate to the clicked page.

However, CGContextDrawPDFPage seems to be using copious amounts of memory when attempting to draw the page. Even though the image is only supposed to be around 100px tall, the application crashes while drawing one page in particular, which according to Instruments, allocates about 13 MB of memory just for the one page.

Here's the code for drawing:

//Note: This is always called in a background thread, but the autorelease pool is setup elsewhere
+ (void) drawPage:(CGPDFPageRef)m_page inRect:(CGRect)rect inContext:(CGContextRef) g { 
    CGPDFBox box = kCGPDFMediaBox;
    CGAffineTransform t = CGPDFPageGetDrawingTransform(m_page, box, rect, 0,YES);
    CGRect pageRect = CGPDFPageGetBoxRect(m_page, box);

    //Start the drawing
    CGContextSaveGState(g);

    //Clip to our bounding box
    CGContextClipToRect(g, pageRect);   

    //Now we have to flip the origin to top-left instead of bottom left
    //First: flip y-axix
    CGContextScaleCTM(g, 1, -1);
    //Second: move origin
    CGContextTranslateCTM(g, 0, -rect.size.height);

    //Now apply the transform to draw the page within the rect
    CGContextConcatCTM(g, t);

    //Finally, draw the page
    //The important bit.  Commenting out the following line "fixes" the crashing issue.
    CGContextDrawPDFPage(g, m_page);

    CGContextRestoreGState(g);
}

Is there a better way to draw this image that doesn't take up huge amounts of memory?

like image 901
Ed Marty Avatar asked Jun 04 '10 14:06

Ed Marty


1 Answers

Try to add :

CGContextSetInterpolationQuality(g, kCGInterpolationHigh);
CGContextSetRenderingIntent(g, kCGRenderingIntentDefault); 

before :

CGContextDrawPDFPage(g, m_page);

I had a similar issue and adding the 2 function call above resulted in the rendering using 5x less memory. Might be a bug in the CGContextXXX drawing functions

like image 180
Johann Avatar answered Sep 29 '22 12:09

Johann