我有一个来自PDF的NSImage,所以它有一个类型为NSPDFImageRep的表示。我做了一个镜像setDataRetained:是的;以确保它仍然是一个NSPDFImageRep。稍后,我想要更改页面,因此我获得了代表,并设置了当前页面。这很好。
问题是,当我绘制图像时,只有第一页出来。
我的印象是,当我绘制NSImage时,它会选择一个表示,然后绘制该表示。现在,图像只有一个表示,所以这就是正在绘制的那个,也就是PDFrep。那么,为什么当我绘制图像时,它没有绘制正确的页面呢?
但是,当我绘制表示本身时,我得到了正确的页面。
我遗漏了什么?
发布于 2009-12-16 20:52:08
第一次显示NSImageRep时,NSImage会对其进行缓存。对于NSPDFImageRep,"setCacheMode:“消息不起作用。因此,将显示的页面将始终是第一页。有关详细信息,请参阅this guide。
然后,您有两个解决方案:
发布于 2009-12-18 02:36:58
另一种绘制PDF的机制是使用CGPDF*函数。为此,请使用CGPDFDocumentCreateWithURL创建一个CGPDFDocumentRef对象。然后,使用CGPDFDocumentGetPage获取一个CGPDFPageRef对象。然后,您可以使用CGContextDrawPDFPage将页面绘制到图形上下文中。
您可能必须应用转换,以确保文档最终的大小符合您的要求。使用CGAffineTransform和CGContextConcatCTM来完成此操作。
下面是从我的一个项目中摘取的一些示例代码:
// use your own constants here
NSString *path = @"/path/to/my.pdf";
NSUInteger pageNumber = 14;
CGSize size = [self frame].size;
// if we're drawing into an NSView, then we need to get the current graphics context
CGContextRef context = (CGContextRef)([[NSGraphicsContext currentContext] graphicsPort]);
CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)path, kCFURLPOSIXPathStyle, NO);
CGPDFDocumentRef document = CGPDFDocumentCreateWithURL(url);
CGPDFPageRef page = CGPDFDocumentGetPage(document, pageNumber);
// in my case, I wanted the PDF page to fill in the view
// so we apply a scaling transform to fir the page into the view
double ratio = size.width / CGPDFPageGetBoxRect(page, kCGPDFTrimBox).size.width;
CGAffineTransform transform = CGAffineTransformMakeScale(ratio, ratio);
CGContextConcatCTM(context, transform);
// now we draw the PDF into the context
CGContextDrawPDFPage(context, page);
// don't forget memory management!
CGPDFDocumentRelease(document);https://stackoverflow.com/questions/1343824
复制相似问题