如何将我的视图作为图片osx

Col*_*eel 0 macos objective-c

我想把我的NSView(带图层)作为图像我可以在OSX中这样做吗?

在iOS中我会做以下

-(UIImage*) makeImage//snapshot the view
{
    UIGraphicsBeginImageContext(self.view.bounds.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;
}
Run Code Online (Sandbox Code Playgroud)

我从一个SO答案中尝试了这个解决方案

[[NSImage alloc] initWithData:[view dataWithPDFInsideRect:[view bounds]]];
Run Code Online (Sandbox Code Playgroud)

但它不起作用,因为我在我的NSView.

我从将UI转换为NS开始,现在每行都有警告:)

-(NSImage*) makeImage :(RMBlurredView*)view
{
    UIGraphicsBeginImageContext(view.bounds.size);

    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];

    NSImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return viewImage;
}
Run Code Online (Sandbox Code Playgroud)

我不熟悉OSX可以帮助我将这段代码转换成OSX吗?

Dai*_*jan 5

绘制到图像与iOS中有所不同:

  1. 你创建一个空白图像,LOCK到它,所以所有绘图都转到该图形上下文

    NSImage *image = [[NSImage alloc] initWithSize:self.view.bounds.size];
    [image lockFocus];
    
    Run Code Online (Sandbox Code Playgroud)
  2. 你在iOS上绘制你的图层

    CGContextRef ctx = [NSGraphicsContext currentContext].graphicsPort;
    [self.view.layer renderInContext:ctx];
    
    Run Code Online (Sandbox Code Playgroud)
  3. 解锁图像

    [image unlockFocus];
    
    Run Code Online (Sandbox Code Playgroud)

注意这仅适用于您的视图是分层的.它不适用于非分层视图!
您的视图 - 如上所示 - 是图层支持所以一切都很好;)