【发布时间】:2011-09-15 20:07:18
【问题描述】:
我已经编写了从 pdf 文件生成缩略图并将它们保存为 png 图片的代码,但是在 iPad 2 上成功运行的相同代码在 iPad 1 上会崩溃。
加载仪器后,我看到在为六个 pdf 生成图片时,内存使用量一度飙升至 20mb,然后在 CG 绘制完成后它会回落到正常水平,我很确定密集的内存负载导致了崩溃,因为我用加载普通图片替换了那部分代码,它在两个设备上都运行良好。
那么问题来了:如何用CG函数生成pdf缩略图,尽量少占用内存?我正在考虑在后台线程上运行它,但我认为这不会以任何方式优化内存使用...
代码还对缩略图应用了渐变效果,这是功能要求...
代码如下:
+ (UIImage *)imageFromPDFWithDocumentRef:(NSString *)documentPath{
CGPDFDocumentRef documentRef = CGPDFDocumentCreateWithURL((CFURLRef)[NSURL fileURLWithPath:documentPath]);
CGPDFPageRef pageRef = CGPDFDocumentGetPage(documentRef, 1);
CGRect pageRect = CGPDFPageGetBoxRect(pageRef, kCGPDFCropBox);
if(pageRect.size.width >pageRect.size.height){
pageRect.origin.x = (pageRect.size.width - pageRect.size.height)/2;
pageRect.size.width = pageRect.size.height;
}else{
pageRect.origin.y = (pageRect.size.height - pageRect.size.width)/2;
pageRect.size.height = pageRect.size.width;
}
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);
CGGradientRef glossGradient;
CGColorSpaceRef rgbColorspace;
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 1.0, 1.0, 1.0, 0.1, // Start color
0.0, 0.0, 1.0, 0.7 }; // End color
rgbColorspace = CGColorSpaceCreateDeviceRGB();
glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
CGRect currentBounds = pageRect;
CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 800);
CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), 0);
CGContextDrawLinearGradient(context, glossGradient, topCenter, midCenter, 0);
CGGradientRelease(glossGradient);
CGColorSpaceRelease(rgbColorspace);
CGRect thumbRect = CGRectMake(0, 0, 187, 187);
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGPDFDocumentRelease(documentRef);
return [UICommon resizedImage:finalImage rect:thumbRect];
}
谢谢!
【问题讨论】:
标签: iphone ipad pdf thumbnails