我正在创建一个将 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/