【发布时间】:2014-04-20 03:33:27
【问题描述】:
我有一个 PDF 文件,我需要将 PDF 中的每一页提取为UIImage,然后根据用户设置更改UIImage 的颜色并将其加载到UICollectionViewCell。我有一些如何设法做到这一点并避免生涩的滚动,我预加载了一些图像并在页面通过时释放它们。但是一旦图像被渲染,它就会占用大量内存,并且渲染时间也相当长。请看一下我做的一段代码
-(UIImage *)getImageFromPDF:(int)pg withColor:(int)color{
// create PDF document
CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:pdfPath]);
// get the first page
CGPDFPageRef page = CGPDFDocumentGetPage(document, pg);
// create a bitmap context
CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CGFloat pdfScale = 1.0f;//self.view.frame.size.width/pageRect.size.width;
pageRect.size = CGSizeMake(pageRect.size.width * pdfScale, pageRect.size.height * pdfScale);
UIGraphicsBeginImageContextWithOptions(pageRect.size, YES, pdfScale);
// flip the context
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, pageRect.size.height);
CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1, -1);
// draw the page into the bitmap context
CGContextDrawPDFPage(UIGraphicsGetCurrentContext(), page);
CGPDFDocumentRelease(document);
// get the image from the context
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if(color==1)
return image;
else
{
CGRect contextRect;
contextRect.origin.x = 0.0f;
contextRect.origin.y = 0.0f;
contextRect.size = [image size];
// Retrieve source image and begin image context
CGSize itemImageSize = [image size];
CGPoint itemImagePosition;
itemImagePosition.x = ceilf((contextRect.size.width - itemImageSize.width) / 2);
itemImagePosition.y = ceilf((contextRect.size.height - itemImageSize.height) );
UIGraphicsBeginImageContext(contextRect.size);
CGContextRef c = UIGraphicsGetCurrentContext();
// Setup shadow
// Setup transparency layer and clip to mask
//CGContextBeginTransparencyLayer(c, NULL);
CGContextScaleCTM(c, 1.0, -1.0);
CGContextClipToMask(c, CGRectMake(itemImagePosition.x, -itemImagePosition.y, itemImageSize.width, -itemImageSize.height), [image CGImage]);
switch (color) {
case 1:
CGContextSetRGBFillColor(c, 1, 1, 1, 1);
break;
case 2:
CGContextSetRGBFillColor(c, 0, 0, 0, 1);
break;
case 3:
CGContextSetRGBFillColor(c, 0.95686, 0.929412, 0.85098, 1);
break;
default:
CGContextSetRGBFillColor(c, 1, 1, 1, 1);
break;
}
contextRect.size.height = -contextRect.size.height;
contextRect.size.height -= 15;
// Fill and end the transparency layer
CGContextFillRect(c, contextRect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
}
谁能帮我减少内存使用和渲染时间,以便用户可以流畅地滚动页面。我将页码和颜色选项传递给函数
-(UIImage *)getImageFromPDF:(int)pg withColor:(int)color
颜色选项 1 是从 PDF 中提取的图像的默认颜色,因此会跳过着色部分并立即返回 UIImage。
这是有效的,但需要相当长的时间。非常感谢任何帮助
【问题讨论】:
标签: ios objective-c pdf image-processing uiimage