2009-02-06 133 views
2

我想裁剪包含PDF的NSImage。在打印时,我使用NSImage的drawInRect来让它只绘制我需要的东西 - 而且这个效果很好。NSImage - 裁剪PDF后模糊

但是,现在我试图创建一个裁剪区域的新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中是模糊的,不再适用于印刷。有任何想法吗?

回答

5

lockFocus/unlockFocus执行光栅绘制到图像的缓存。这就是为什么它是“模糊” - 它的分辨率低,可能注册不正确。你需要矢量绘图。

使用PDF工具包。首先,将每个页面的裁切框设置为您的矩形。然后,您应该能够从PDFDocument的dataRepresentation创建裁剪的NSImage。

2

下面是执行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]]; 
+1

确保您正式发布或autoreleasePDF和theCroppedImage。 – 2009-02-07 02:06:55