gpt4 book ai didi

macos - cocoa :如何将 View 渲染为图像?

转载 作者:行者123 更新时间:2023-12-03 16:05:54 25 4
gpt4 key购买 nike

我想知道有什么方法可以将 View 渲染为图像吗?就像屏幕截图一样,但我可以为该方法指定任何 View 。我知道如何在ios中做到这一点。 Saving view content ,但是我怎样才能在 mac os 中做到这一点呢?

最佳答案

有多种方法,但没有一种方法是完美的。许多问题都与图层支持的 View 有关。

如果您没有图层支持或托管 View ,您可以使用以下代码:

    NSData* data = [mainView dataWithPDFInsideRect:[mainView bounds]];
NSImage *img = [[NSImage alloc] initWithData:data];

如果您使用基于图层的 View :

直到 10.8 对我来说最好的方法是

        NSSize mySize = mapImage.bounds.size;
NSSize imgSize = NSMakeSize( mySize.width, mySize.height );
NSBitmapImageRep *bir = [mapImage bitmapImageRepForCachingDisplayInRect:[mapImage bounds]];
[bir setSize:imgSize];
[mapImage cacheDisplayInRect:[mapImage bounds] toBitmapImageRep:bir];
caheImg = [[NSImage alloc]initWithSize:imgSize];
[caheImg addRepresentation:bir];

但在 10.8 bitmapImageRepForCachingDisplayInRect 中,停止使用图层支持的 View 。

有一个选项可以制作屏幕截图并剪切 View :

+ (NSImage*) screenCacheImageForView:(NSView*)aView
{
NSRect originRect = [aView convertRect:[aView bounds] toView:[[aView window] contentView]];

NSRect rect = originRect;
rect.origin.y = 0;
rect.origin.x += [aView window].frame.origin.x;
rect.origin.y += [[aView window] screen].frame.size.height - [aView window].frame.origin.y - [aView window].frame.size.height;
rect.origin.y += [aView window].frame.size.height - originRect.origin.y - originRect.size.height;

CGImageRef cgimg = CGWindowListCreateImage(rect,
kCGWindowListOptionIncludingWindow,
(CGWindowID)[[aView window] windowNumber],
kCGWindowImageDefault);
return [[NSImage alloc] initWithCGImage:cgimg size:[aView bounds].size];
}

关于macos - cocoa :如何将 View 渲染为图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11948241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com