提高iPhone上PDF渲染性能

3

我有一个UITableView,在每个单元格中都显示了从PDF创建的UIImage。但是现在性能非常差。这是我用于从PDF生成UIImage的代码。

在cellForRowAtIndexPath方法中创建CGPDFDocumentRef和UIImageView:

...    
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), (CFStringRef)formula.icon, NULL, NULL);
CGPDFDocumentRef documentRef = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
CFRelease(pdfURL);
UIImageView *imageView = [[UIImageView alloc] initWithImage:[self imageFromPDFWithDocumentRef:documentRef]];
...

生成UIImage:

- (UIImage *)imageFromPDFWithDocumentRef:(CGPDFDocumentRef)documentRef {
    CGPDFPageRef pageRef = CGPDFDocumentGetPage(documentRef, 1);
    CGRect pageRect = CGPDFPageGetBoxRect(pageRef, kCGPDFCropBox);

    UIGraphicsBeginImageContext(pageRect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, CGRectGetMinX(pageRect),CGRectGetMaxY(pageRect));
    CGContextScaleCTM(context, 1, -1);  
    CGContextTranslateCTM(context, -(pageRect.origin.x), -(pageRect.origin.y));
    CGContextDrawPDFPage(context, pageRef);

    UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return finalImage;
} 

我该如何提高速度并保持内存低?


嗨,我正在做和你一样的事情。我不知道你代码中的formula.icon是什么,请问你能提供更多信息吗?谢谢。 - Fire Fist
1个回答

3
在运行时为每个单元格从PDF生成图像似乎会对性能造成巨大的影响。您应该考虑在后台线程中执行实际渲染并存储渲染结果UIImages,并在运行时将其填充到UITableView中。这将至少释放UI线程并增加应用程序的响应性。
对于尚未渲染的单元格,您可以显示“加载”消息或添加“活动指示器”旋转器。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接