由于 iOS 错过了 PDFKit.framework,我猜想 UIImage 有限/损坏的 PDF 支持的问题在于它不应该首先获得任何支持,在这方面我报告了它的有限支持作为一个错误(rdar:8338627),它也是 IB 中的一个错误,渲染支持可能是从 osx 继承的。
我已经决定在上下文中手动渲染 pdf,然后将其保存到 UIImage,其代码如下(在 iOS 3.x 和 4.x 上测试)
#include <dlfcn.h>
-(UIImage *)UIImageFromPDF:(NSString*)fileName size:(CGSize)size{
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), (CFStringRef)fileName, NULL, NULL);
if (pdfURL) {
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL(pdfURL);
CFRelease(pdfURL);
//create context with scaling 0.0 as to get the main screen's if iOS4+
if (dlsym(RTLD_DEFAULT,"UIGraphicsBeginImageContextWithOptions") == NULL) {
UIGraphicsBeginImageContext(size);
}else {
UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
}
CGContextRef context = UIGraphicsGetCurrentContext();
//translate the content
CGContextTranslateCTM(context, 0.0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSaveGState(context);
//scale to our desired size
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 1);
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, CGRectMake(0, 0, size.width, size.height), 0, true);
CGContextConcatCTM(context, pdfTransform);
CGContextDrawPDFPage(context, page);
CGContextRestoreGState(context);
//return autoreleased UIImage
UIImage *ret = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGPDFDocumentRelease(pdf);
return ret;
}else {
NSLog(@"Could not load %@",fileName);
}
return nil;
}