我有一个来自 PDF 的 NSImage,因此它有一种 NSPDFImageRep 类型的表示形式。我做了一个图像 setDataRetained:YES;以确保它仍然是 NSPDFImageRep。后来,我想更改页面,所以我得到了代表,并设置了当前页面。这很好。
问题是当我绘制图像时,只显示第一页。
我的印象是,当我绘制 NSImage 时,它会选择一个表示并绘制该表示。现在,该图像只有一个代表,因此这就是正在绘制的代表,即 PDFrep。那么,为什么当我绘制图像时,它没有绘制正确的页面呢?
然而,当我绘制表示本身时,我得到了正确的页面。
我缺少什么?
I have an NSImage that came from a PDF, so it has one representation, of type NSPDFImageRep. I do an image setDataRetained:YES; to make sure that it remains a NSPDFImageRep. Later, I want to change the page, so I get the rep, and set the current page. This is fine.
The problem is that when I draw the image, only the 1st page comes out.
My impression is that when I draw an NSImage, it picks a representation, and draws that representation. Now, the image only has one rep, so that's the one that is being drawn, and that's the PDFrep. So, why when I draw the image, is it not drawing the correct page?
HOWEVER, when I draw the representation itself, I get the correct page.
What am I missing?
发布评论
评论(2)
NSImage 在第一次显示时会对 NSImageRep 进行缓存。对于 NSPDFImageRep,“setCacheMode:”消息无效。因此,将显示的页面将始终是第一页。请参阅 本指南了解更多信息。
那么您有两种解决方案:
NSImage does a caching of the NSImageRep, when first displayed. In the case of NSPDFImageRep, the "setCacheMode:" message has no effect. Thus, the page that will be displayed will always be the first page. See this guide for more information.
You have then two solutions:
绘制 PDF 的另一种机制是使用 CGPDF* 函数。为此,请使用 CGPDFDocumentCreateWithURL 创建一个 CGPDFDocumentRef 对象。然后,使用
CGPDFDocumentGetPage
获取CGPDFPageRef
对象。然后,您可以使用 CGContextDrawPDFPage 将页面绘制到图形上下文中。您可能必须应用转换以确保文档最终的大小符合您的要求。使用
CGAffineTransform
和CGContextConcatCTM
来执行此操作。以下是从我的一个项目中提取的一些示例代码:
An alternative mechanism to draw a PDF is to use the CGPDF* functions. To do this, use
CGPDFDocumentCreateWithURL
to create aCGPDFDocumentRef
object. Then, useCGPDFDocumentGetPage
to get aCGPDFPageRef
object. You can then useCGContextDrawPDFPage
to draw the page into your graphics context.You may have to apply a transform to ensure that the document ends up sized like you want. Use a
CGAffineTransform
andCGContextConcatCTM
to do this.Here is some sample code pulled out of one of my projects: