iPhone:CoreGraphics和内存管理

时间:2010-04-07 16:01:06

标签: iphone cgcontext core-graphics cgpdfdocument

有人能告诉我这里做错了什么吗?我使用此方法翻阅PDF中的页面。但是代码中的某些内容似乎无法正确发布,因为每次我拉一个包含图像的PDF页面时我的内存占用都会增加。我是CoreGraphics的新手,并且在我的生活中无法弄清楚这种方法会泄漏内存的位置。

-(UIImage *)pageAtIndex:(NSInteger)pageNumber withWidth:(CGFloat)width andHeight:(CGFloat)height {
    if((pageNumber>0) && (pageNumber<=pageCount)) {
        CGFloat scaleRatio; // multiplier by which the PDF Page will be scaled

        UIGraphicsBeginImageContext(CGSizeMake(width, height)); 
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGPDFPageRef page = CGPDFDocumentGetPage(pdf, pageNumber);
        CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFBleedBox);

        //Figure out the orientation of the PDF page and set the scaleRatio accordingly
        if(pageRect.size.width/pageRect.size.height < 1.0) {
            scaleRatio = height/pageRect.size.height;
        } 
        else {
            scaleRatio = width/pageRect.size.width;     
        }

        //Calculate the offset to center the image
        CGFloat xOffset = 0.0;
        CGFloat yOffset = height;
        if(pageRect.size.width*scaleRatio<width) {
            xOffset = (width/2)-(pageRect.size.width*scaleRatio/2);
        }
        else {
            yOffset = height-((height/2)-(pageRect.size.height*scaleRatio/2));  
        }
        CGContextTranslateCTM(context, xOffset, yOffset);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextSaveGState(context);
        CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFBleedBox, CGRectMake(0, 0, pageRect.size.width, pageRect.size.height), 0, true);
        pdfTransform = CGAffineTransformScale(pdfTransform, scaleRatio, scaleRatio);

        CGContextConcatCTM(context, pdfTransform);
        CGContextDrawPDFPage(context, page);

        UIImage *tempImage = UIGraphicsGetImageFromCurrentImageContext();

        CGContextRestoreGState(context);
        UIGraphicsEndPDFContext();
        UIGraphicsEndImageContext();

        return tempImage;
    }
    return nil;
}

2 个答案:

答案 0 :(得分:1)

我想我已经解决了这个问题,感谢Apple核心图形邮件列表上的人们。似乎CGPDFDocument在调用之间缓存数据但从不释放它。这似乎是CoreGraphics中的一个错误。我被告知,唯一真正的方法是每次拉页时加载和卸载PDF。

答案 1 :(得分:1)

你可能没有发布一些东西。要检查CGPDFPageRetain(<CGPDFPageRef page>)CGPDFPageRelease(<CGPDFPageRef page>)等内容。

相关问题