首页 文章

从屏幕外NSView生成缩放图像

提问于
浏览
6

我在Cocoa应用程序中有一系列屏幕外NSView,用于组合PDF进行打印 . 这些观点不在NSWindow中,也不以任何方式显示 .

我希望能够生成该视图的缩略图,就像PDF看起来一样,但缩小到适合某个像素大小(约束到宽度或高度) . 这需要尽可能快,所以我想避免渲染为PDF,然后转换为光栅和缩放 - 我想直接去光栅 .

目前我正在做:

NSBitmapImageRep *bitmapImageRep = [pageView bitmapImageRepForCachingDisplayInRect:pageView.bounds];
[pageView cacheDisplayInRect:pageView.bounds toBitmapImageRep:bitmapImageRep];
NSImage *image = [[NSImage alloc] initWithSize:bitmapImageRep.size];
[image addRepresentation:bitmapImageRep];

这种方法运行良好,但我无法弄清楚如何在渲染bitmapImageRep之前将缩放应用于NSView . 我想避免使用 scaleUnitSquareToSize ,因为据我所知,它只会改变边界,而不是NSView的框架 .

有关最佳方法的任何建议吗?

2 回答

  • 6

    这就是我最终做的,它完美地运作 . 我们直接绘制到 NSBitmapImageRep ,但事先使用 CGContextScaleCTM 显式缩放上下文 . graphicsContext.graphicsPortNSGraphicsContext 提供了 CGContextRef 的句柄 .

    NSView *pageView = [self viewForPageIndex:pageIndex];
    
    float scale = width / pageView.bounds.size.width;
    float height = scale * pageView.bounds.size.height;
    
    NSRect targetRect = NSMakeRect(0.0, 0.0, width, height);
    NSBitmapImageRep *bitmapRep;
    
    bitmapRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
                                                        pixelsWide:targetRect.size.width
                                                        pixelsHigh:targetRect.size.height
                                                     bitsPerSample:8
                                                   samplesPerPixel:4
                                                          hasAlpha:YES
                                                          isPlanar:NO
                                                    colorSpaceName:NSCalibratedRGBColorSpace
                                                      bitmapFormat:0
                                                       bytesPerRow:(4 * targetRect.size.width)
                                                      bitsPerPixel:32];
    
    [NSGraphicsContext saveGraphicsState];
    
    NSGraphicsContext *graphicsContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmapRep];
    [NSGraphicsContext setCurrentContext:graphicsContext];
    CGContextScaleCTM(graphicsContext.graphicsPort, scale, scale);
    
    [pageView displayRectIgnoringOpacity:pageView.bounds inContext:graphicsContext];
    
    [NSGraphicsContext restoreGraphicsState];
    
    NSImage *image = [[NSImage alloc] initWithSize:bitmapRep.size];
    [image addRepresentation:bitmapRep];
    
    return image;
    
  • 0

    如何使用 scaleUnitSquareToSize: 然后传入一个较小的矩形到 bitmapImageRepForCachingDisplayInRect:cacheDisplayInRect:toBitmapImageRep:

    所以,如果你将它缩小2倍,你就会将一个矩形传递给一半有边界和高度 .

相关问题