我正在试着裁剪一个包含PDF的NSImage。在打印时,我使用NSImage的drawInRect让它只绘制我需要的内容--这很好用。
但是,现在我只想创建一个裁剪过的区域的新NSImage。我玩了一段时间,然后在CocoaBuilder上找到了下面的代码:
- (NSImage *) imageFromRect: (NSRect) rect
{
NSAffineTransform * xform = [NSAffineTransform transform];
// translate reference frame to map rectangle 'rect' into first quadrant
[xform translateXBy: -rect.origin.x
yBy: -rect.origin.y];
NSSize canvas_size = [xform transformSize: rect.size];
NSImage * canvas = [[NSImage alloc] initWithSize: canvas_size];
[canvas lockFocus];
[xform concat];
// Get NSImageRep of image
NSImageRep * rep = [self bestRepresentationForDevice: nil];
[rep drawAtPoint: NSZeroPoint];
[canvas unlockFocus];
return [canvas autorelease];
}这是可行的,但是返回的NSImage比较模糊,不再适合打印。有什么想法吗?
发布于 2009-02-07 00:27:22
lockFocus/unlockFocus对图像的缓存执行光栅绘制。这就是为什么它是“模糊的”-它是低分辨率的,可能是错误的注册。你需要矢量绘图。
使用PDF工具包。首先,将每个页面的裁剪框设置为矩形。然后,您应该能够从PDFDocument的dataRepresentation创建裁剪后的NSImage。
发布于 2009-02-07 01:46:35
这是执行Peter Hosey回答的代码。谢谢!
PDFDocument *thePDF = [[PDFDocument alloc] initWithData:pdfData];
PDFPage *thePage = [thePDF pageAtIndex:0];
NSRect pageCropRect = NSMakeRect(0, 100, 100, 100);
[thePage setBounds:pageCropRect forBox:kPDFDisplayBoxMediaBox];
NSImage *theCroppedImage = [[NSImage alloc] initWithData:[thePage dataRepresentation]];https://stackoverflow.com/questions/522639
复制相似问题