objective-c - 使用 drawRect 和 drawLayerInContext 在 iOS 中渲染 PDF

标签 objective-c ios pdf uiview core-graphics

我正在创建一个将 PDF 渲染到其边界矩形的自定义 View 。
我已经粘贴了下面的代码:

CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);
CGContextFillRect(context, self.bounds);

CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CGFloat scale = MIN(self.bounds.size.width / pageRect.size.width, self.bounds.size.height / pageRect.size.height);
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextScaleCTM(context, scale, scale);    
CGContextDrawPDFPage(context, self.page);
CGContextRestoreGState(context);

我的问题是,如果我在 drawRect 方法中使用上面的代码,它只会给我一个黑色矩形。如果我在 drawLayer:inContext: 方法中使用它,它工作正常。可能是什么原因 ?

PS:在使用 drawRect 时,我使用方法 UIGraphicsGetCurrentContext() 来获取当前图形上下文。

最佳答案

这段代码实际上对我来说很好.. 添加断点并检查它是否命中 -drawrect 方法

 CGContextRef context = UIGraphicsGetCurrentContext();
NSString *filePath = [[NSBundle mainBundle]
                      pathForResource:@"Trial" ofType:@"pdf"];
NSURL *url = [[NSURL alloc] initFileURLWithPath:filePath];
CGPDFDocumentRef document = [self openDocument:(CFURLRef)url];
[url release];

CGPDFPageRef docPageRef =CGPDFDocumentGetPage(document, 1);

CGContextSetRGBFillColor(context, 1.0,1.0,1.0,1.0);
CGContextFillRect(context, self.bounds);

CGRect pageRect = CGPDFPageGetBoxRect(docPageRef, kCGPDFMediaBox);
CGFloat scale = MIN(self.bounds.size.width / pageRect.size.width, self.bounds.size.height / pageRect.size.height);
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextScaleCTM(context, scale, scale);
CGContextDrawPDFPage(context, docPageRef);
CGContextRestoreGState(context);

我在我的 drawrect 中使用了它并且工作正常。

检查所有引用是否都获得了您提供给 drawrect 的值 check this

关于objective-c - 使用 drawRect 和 drawLayerInContext 在 iOS 中渲染 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12477156/

相关文章:

ios - UICollectionViewCell Spacing 设置为 0 但仍然有间距

ios - Watchkit:如何在 Objective c 中从左到右循环图像?

java - 使用 Java 启用 PDF 快速 Web 查看?

javascript - ASP.NET - 打开 PDF 并检测到用户滚动到底部

ios - 如何在从主函数返回值之前等待委托(delegate)函数完成

ios - 在 ios 4.3 + iphone sdk 的 textview 中自动滚动

ios - 在spritekit中制作一个松紧带式弹弓

ios - Twilio iOS SDK 在去电时失败并显示 "400 Bad request"

如果字段多次出现在 PDF 表单中,Java PDFBox 不会维护该字段的字体外观

iphone - 将文本添加到 UIWebView 文本框