【问题标题】:Capture NSBox Subclass to PNG将 NSBox 子类捕获为 PNG
【发布时间】:2011-11-04 21:16:38
【问题描述】:

我目前正在尝试将我的 NSBox 子类的内容捕获到 PNG 文件中。我发现了一些似乎可以完美解决问题的代码(我从我的实际子类中调用的代码):

[self lockFocus];

NSBitmapImageRep *rep = [self bitmapImageRepForCachingDisplayInRect:[self bounds]];

[self cacheDisplayInRect:[self bounds] toBitmapImageRep:rep];

[self unlockFocus];

NSData *imageData = [rep representationUsingType:NSPNGFileType properties:nil];

[imageData writeToFile:@"~/Desktop/test.png" atomically:NO];    

正如我所说,该代码运行良好,但只有一个小问题:NSBox 实际上是透明的,因此对于习惯了默认的白灰色背景的用户来说,图像看起来很奇怪。

我还没有成功地从我的主 AppDelegate 调用它。这应该可以解决问题,同时捕获 NSBox 背后的内容,但它对我不起作用。

有谁知道如何捕捉这个 NSBox 背后的任何东西及其内容?

【问题讨论】:

    标签: objective-c capture nsbox


    【解决方案1】:

    虽然效率不高,但您可以尝试在 NSBox 子类中手动绘制窗口背景:

    - (void) drawRect:(NSRect)dirtyRect {
    
        NSDrawWindowBackground(dirtyRect);
        [super drawRect:dirtyRect];
    }
    

    【讨论】:

      【解决方案2】:

      你能从 windows 的角度捕捉 NSBox 的矩形吗?

      【讨论】:

      • 这就是我想要的,但我不知道如何从我的主 NSWindow 引用 NSView。