Objective c NSImageRep混乱
我有一个来自PDF的NSImage,所以它有一个NSPDIMAGEREP类型的表示。我做了一个图像设置:是;以确保它仍然是NSPDIMAGEREP。稍后,我想更改页面,因此我获得代表,并设置当前页面。这很好 问题是,当我绘制图像时,只有第一页出现 我的印象是,当我画一个NSImage时,它会选择一个表示,然后画那个表示。现在,图像只有一个rep,这就是正在绘制的,这就是PDFrep。那么,为什么我在绘制图像时,它绘制的页面不正确 然而,当我绘制表示本身时,我得到了正确的页面Objective c NSImageRep混乱,objective-c,nsimage,nsimagerep,Objective C,Nsimage,Nsimagerep,我有一个来自PDF的NSImage,所以它有一个NSPDIMAGEREP类型的表示。我做了一个图像设置:是;以确保它仍然是NSPDIMAGEREP。稍后,我想更改页面,因此我获得代表,并设置当前页面。这很好 问题是,当我绘制图像时,只有第一页出现 我的印象是,当我画一个NSImage时,它会选择一个表示,然后画那个表示。现在,图像只有一个rep,这就是正在绘制的,这就是PDFrep。那么,为什么我在绘制图像时,它绘制的页面不正确 然而,当我绘制表示本身时,我得到了正确的页面 我缺少什么?NSIm
我缺少什么?NSImage在第一次显示时缓存NSImageRep。对于NSPDIMAGEREP,“setCacheMode:”消息无效。因此,将显示的页面将始终是第一页。有关更多信息,请参阅 然后有两种解决方案:
绘制PDF的另一种机制是使用CGPDF*函数。为此,请使用
CGPDFDocumentCreateWithURL
创建CGPDFDocumentRef
对象。然后,使用CGPDFDocumentGetPage
获取cgpdfageref
对象。然后可以使用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);