我有一个要打印的自定义 NSView。在使用 NSView 和打印选项进行设置后,我进行了以下调用:
NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView: printView printInfo: printInfo];
[NSPrintOperation setCurrentOperation: printOperation];
[printView beginDocument];
NSGraphicsContext* theContext = printOperation.context;
“theContext”始终为零。如果我忽略这一点,当我拨打这个电话时:
[printView beginPageInRect: rect atPlacement: location];
我得到一个例外,说:“[General] lockFocus/unlockFocus 发送到不在窗口中的视图”
如果我将其注释掉,我会收到大约十亿条消息:“CGContextDrawPath:无效上下文 0x0。如果您想查看回溯,请设置 CG_CONTEXT_SHOW_BACKTRACE 环境变量。” 打开回溯只会显示我所有的绘图都是导致它的原因。
如果我查看视图的“DrawRect:”函数中的图形上下文:
NSGraphicsContext *graphicsContext = [NSGraphicsContext currentContext];
CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
graphicsContext 和 context 都为零。
那么,我该怎么做才能获得有效的打印上下文?我看到有一个 NSPrintOperation 方法 createContext,但文档说不要直接调用它,如果我忽略它,它没有帮助,并且向打印机拍摄大约八个空作业。
最新版本的代码,仍然导致空上下文:
NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView: printView printInfo: printInfo];
[printView setCurrentForm: [formSet objectAtIndex: 0]];
NSInteger pageCounter = 0;
formHeight = 0;
formWidth = 0;
for (AFVForm *oneForm in formSet)
{
printView.verticalOffset = formHeight;
NSRect rect = NSMakeRect(0, 0, oneForm.pageWidth, oneForm.pageHeight);
NSPoint location = [printView locationOfPrintRect: rect];
formHeight += [oneForm pageHeight];
if ([oneForm pageWidth] > formWidth)
formWidth = [oneForm pageWidth];
pageCounter++;
printView.currentForm = oneForm;
[printView setPrintMode: YES];
[printView drawRect: NSZeroRect];
[printView setPrintMode: NO];
}
[printOperation setShowsPrintPanel:YES];
[printOperation runOperationModalForWindow: [self window] delegate: nil didRunSelector: nil contextInfo: nil];