我正在将Cocoa-Java代码迁移到Cocoa + JNI,因为Cocoa-Java已被弃用。代码打印存储在文件中的图像。新的Cocoa代码基本上是:
NSImage *image = [[NSImage alloc] initWithContentsOfFile:spoolFile];
if ( [image isValid] ) {
NSImageView *view = [[NSImageView alloc] init];
[view setImage:image];
[view setImageScaling:NSScaleProportionally];
NSPoint p;
NSSize s;
p.x = static_cast<float>( boundsX );
p.y = static_cast<float>( boundsY );
[view setBoundsOrigin:p];
s.width = static_cast<float>( boundsWidth );
s.height = static_cast<float>( boundsHeight );
[view setBoundsSize:s];
NSPrintInfo *info = [NSPrintInfo sharedPrintInfo];
[info setHorizontalPagination:NSClipPagination];
[info setVerticalPagination:NSClipPagination];
[info setHorizontallyCentered:NO];
[info setVerticallyCentered:NO];
p.x = static_cast<float>( boundsX );
p.y = static_cast<float>( [info paperSize].height - boundsHeight - boundsY );
[view translateOriginToPoint:p];
NSPrintOperation *printOp =
[NSPrintOperation printOperationWithView:view printInfo:info];
[printOp setShowsPrintPanel:NO];
[printOp runOperation];
}
运行此代码最终会崩溃:
Thread 0 Crashed:
0 com.apple.AppKit 0x9484ac75 -[NSConcretePrintOperation(NSInternal) _tryToSetCurrentPageNumber:] + 345
1 com.apple.AppKit 0x948d88cf -[NSView(NSPrintingInternal) _printForCurrentOperation] + 524
2 com.apple.AppKit 0x948d85c5 -[NSConcretePrintOperation _renderView] + 358
3 com.apple.AppKit 0x9491f0c0 -[NSConcretePrintOperation runOperation] + 362
为什么呢?如何只打印存储在文件中的图像?
答案 0 :(得分:2)
NSImageView *view = [[NSImageView alloc] init];
那是无效的。您需要使用initWithFrame:
初始化视图。您可能希望传递一个由NSZeroPoint
和图像大小组成的帧。
关于setBoundsOrigin:
和setBoundsSize:
的使用:我不确定这些是否可行,假设您要裁剪图像。您可以尝试它们(在解决上述问题之后),但我觉得从旧版本的所需部分创建新图像会更安全。您可以通过创建所需大小的空图像,锁定焦点,在新图像的原点绘制旧图像的正确部分,并将焦点解锁到新图像,然后给出新图像而不是旧的到图像视图。
答案 1 :(得分:-1)
这是第二次分配给 p.y
时的拼写错误吗?它看起来不像你定义info
直到2行......
此外,通过传递ints而不是手动构建它们并使用static_cast<float>
来使用NSMakePoint()和NSMakeSize()会不会更简单?这似乎是一种非常C ++的方法......
例如,这样的事情可以起作用吗?
NSImage *image = [[NSImage alloc] initWithContentsOfFile:spoolFile];
if ([image isValid]) {
NSPrintInfo *info = [NSPrintInfo sharedPrintInfo];
[info setHorizontalPagination:NSClipPagination];
[info setVerticalPagination:NSClipPagination];
[info setHorizontallyCentered:NO];
[info setVerticallyCentered:NO];
NSImageView *view = [[NSImageView alloc] init];
[view setImage:image];
[view setImageScaling:NSScaleProportionally];
[view setBoundsOrigin:NSMakePoint(boundsX, boundsY)];
[view setBoundsSize:NSMakeSize(boundsWidth, boundsHeight)];
[view translateOriginToPoint:NSMakePoint(boundsX, [info paperSize].height -
boundsHeight - boundsY)];
NSPrintOperation *printOp = [NSPrintOperation printOperationWithView:view printInfo:info];
[printOp setShowsPrintPanel:NO];
[printOp runOperation];
}