1

我有一个 NSImage,用 PDF 数据初始化,创建如下:

NSData* data = [view dataWithPDFInsideRect:view.bounds];
slideImage = [[NSImage alloc] initWithData:data];

现在slideImage是 的大小view

当我尝试在NSImageView. 我尝试将 设置cacheModeNSImageCacheNever,这也不起作用。图像中唯一的图像代表是 PDF,当我将其渲染为 PDF 文件时,它显示它是矢量。

作为一种解决方法,我创建了NSBitmapImageRep一个不同大小的图像,调用drawInRect原始图像,并将位图表示放入一个新图像中NSImage并渲染它,这可行,但感觉它不是最佳的:

- (NSBitmapImageRep*)drawToBitmapOfWidth:(NSInteger)width
                               andHeight:(NSInteger)height
                               withScale:(CGFloat)scale
{
    NSBitmapImageRep *bmpImageRep = [[NSBitmapImageRep alloc]
                                     initWithBitmapDataPlanes:NULL
                                     pixelsWide:width * scale
                                     pixelsHigh:height * scale
                                     bitsPerSample:8
                                     samplesPerPixel:4
                                     hasAlpha:YES
                                     isPlanar:NO
                                     colorSpaceName:NSCalibratedRGBColorSpace
                                     bitmapFormat:NSAlphaFirstBitmapFormat
                                     bytesPerRow:0
                                     bitsPerPixel:0
                                     ];
    bmpImageRep = [bmpImageRep bitmapImageRepByRetaggingWithColorSpace:
                   [NSColorSpace sRGBColorSpace]];
    [bmpImageRep setSize:NSMakeSize(width, height)];
    NSGraphicsContext *bitmapContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:bmpImageRep];
    [NSGraphicsContext saveGraphicsState];
    [NSGraphicsContext setCurrentContext:bitmapContext];

    [self drawInRect:NSMakeRect(0, 0, width, height) fromRect:NSZeroRect operation:NSCompositeCopy fraction:1];

    [NSGraphicsContext restoreGraphicsState];
    return bmpImageRep;
}

- (NSImage*)rasterizedImageForSize:(NSSize)size
{
    NSImage* newImage = [[NSImage alloc] initWithSize:size];
    NSBitmapImageRep* rep = [self drawToBitmapOfWidth:size.width andHeight:size.height withScale:1];
    [newImage addRepresentation:rep];
    return newImage;
}

我怎样才能让 PDF 在任何尺寸下都能很好地呈现,而不需要像我这样的黑客手段?

4

2 回答 2

1

的关键NSImage是您使用您想要的大小(以磅为单位)创建它。支持表示可以是基于矢量的(例如PDF),并且与NSImage分辨率无关(即它支持每个点的不同像素),但NSImage仍然具有固定大小(以点为单位)。

一个要点NSImage是它将/可以添加缓存表示以加速后续绘图。

如果您需要将 PDF 绘制为多种尺寸,并且想要使用 NSImage,那么您最好为给定的目标尺寸创建 NSImage。如果你愿意,你可以保留NSPDFImageRef周围——我认为这不会为你节省太多。

于 2013-10-30T11:10:11.247 回答
0

我们尝试了以下方法:

NSPDFImageRep* rep = self.representations.lastObject;
return [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL (NSRect dstRect)
{
    [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
    [rep drawInRect:dstRect fromRect:NSZeroRect operation:NSCompositeCopy fraction:1 respectFlipped:YES hints:@{
            NSImageHintInterpolation: @(NSImageInterpolationHigh)
    }];
    return YES;
}];

这在放大时确实会给你带来很好的结果,但在缩小时会导致图像模糊。

于 2013-10-30T13:53:16.740 回答