有没有办法将NSView包含许多带有背景颜色的子视图转换为NSImage?示例代码非常棒
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[_collageView bounds]];
[_collageView unlockFocus];
// NSData *exportedData = [rep representationUsingType:NSJPEGFileType properties:nil];
NSData *exportedData = [rep representationUsingType:NSPNGFileType properties:nil];
NSSavePanel *savepanel = [NSSavePanel savePanel];
savepanel.title = @"Save chart";
[savepanel setAllowedFileTypes:[NSArray arrayWithObject:@"png"]];
[savepanel beginSheetModalForWindow:self.view.window completionHandler:^(NSInteger result)
{
if (NSFileHandlingPanelOKButton == result)
{
NSURL* fileURL = [savepanel URL];
if ([fileURL.pathExtension isEqualToString:@""])
fileURL = [fileURL URLByAppendingPathExtension:@"png"];
[exportedData writeToURL:fileURL atomically:YES];
}
}];
我还使用以下代码
[_collageView lockFocus];
NSBitmapImageRep *bits = [[NSBitmapImageRep alloc]initWithFocusedViewRect: [_collageView bounds]];
[_collageView unlockFocus];
NSImage *image1 = [[NSImage alloc] init];
[image1 addRepresentation: bits];
[self.ImageView setImage:image1];
但没有工作
3 回答
您的方法从Windows服务器复制位图 . 这是视图的渲染内容 . 通常你不想这样做 .
这是将焦点锁定在
NSImage
上的更好方法,它可以构建图形上下文,然后使用-drawRect:
或任何绘图方法绘制到该图像中 . 您可以通过简单地迭代它们来添加子视图 .开始吧
在Safari中输入 .
编辑:在转到子视图之前,您必须为它们执行转换 . 忘了 .
我实际上已经在屏幕外实现了一个视图层次结构的绘制 . 它非常简单,即使对于一个非常简单的视图层次结构,其中所有视图都是子类NSControl并且 - (BOOL)isFlipped {return YES; }
这是该代码的一小部分,它将让您了解这样做的痛苦:
我可以使用以下代码解决我的问题