Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

iphone - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...