如何释放CGContextDrawPDFPage创建的内存

时间:2011-01-07 06:34:04

标签: iphone

这是ipad杂志的应用。我们需要阅读PDF并转换为PNG图像用于thumnail。在转换之前读取PDF(调用CGContextDrawPDFPage)后,内存会快速上升并且永远不会释放直到崩溃。我试过很多方面,但它不起作用。如果有人能提供帮助我真的很感激。

CGContextDrawPDFPage(context,aPage); //这是记忆杀手

以下是完整的代码:

- (UIImage *)image:(CGPDFPageRef)aPage rect:(CGRect)aRect {     CGRect pdfcropBox = CGRectIntegral(CGPDFPageGetBoxRect(aPage,kCGPDFCropBox));

if ((float)pdfcropBox.size.width/(float)pdfcropBox.size.height > 
    (float)aRect.size.width/(float)aRect.size.height) //pdf width too big
{
    aRect.size.height = aRect.size.width * pdfcropBox.size.height / pdfcropBox.size.width;
}
//CGRect pdfcropBox = aRect;    

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL,aRect.size.width,
                                             aRect.size.height,
                                             8,
                                             (int)aRect.size.width * 4,
                                             colorSpace, 
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

CGColorSpaceRelease(colorSpace);
colorSpace = nil;

CGPDFPageRetain(aPage);
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(aPage,
                                                              kCGPDFCropBox,
                                                              CGRectMake(0, 0, aRect.size.width,aRect.size.height),
                                                              0, true);
CGContextSaveGState(context);
CGContextConcatCTM(context, pdfTransform);
CGContextDrawPDFPage(context, aPage);
CGPDFPageRelease (aPage);
aPage = nil;
CGContextRestoreGState(context);    
CGImageRef image = CGBitmapContextCreateImage(context);
UIImage *resultingImage =  [UIImage imageWithCGImage:image];
CGContextClearRect(context, aRect);
CGContextClearRect(context, pdfcropBox);

CGContextRelease(context);
CGImageRelease(image);
context = nil; 

NSLog(@"colorSpace :%d,aPage :%d,context :%d",[colorSpace retainCount],[aPage retainCount],[context retainCount]);
return resultingImage;

}

1 个答案:

答案 0 :(得分:5)

您需要释放并重新打开CGPDFDocument,如此处所述Fast and Lean PDF Viewer for iPhone / iPad / iOs - tips and hints?