将NSView保存到PNG文件?
-
14-11-2019 - |
题
我正在制作一个简单的程序,为我玩的游戏创造游戏卡。我已经把它寄给了我的一些朋友进行测试,但他们真的希望它保存图像,而不仅仅是打印它们。我试图使它另存为.png文件。我在这里有问题。
-
如何使其将我的视图保存为.png文件,包括所有视图的nsimagewells。
-
如何将nspopupbutton添加到NSSavePanel以允许用户选择格式?
任何帮助非常感谢。
解决方案
First create a TIFF representation of your view:
// Get the data into a bitmap.
[self lockFocus];
rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[self bounds]];
[self unlockFocus];
data = [rep TIFFRepresentation];
To support multiple file types, use:
data = [rep representationUsingType:(NSBitmapImageFileType)storageType
properties:(NSDictionary *)properties];
NSBitmapImageFileType is an enum constant specifying a file type for bitmap images. It can be NSBMPFileType, NSGIFFileType, NSJPEGFileType, NSPNGFileType, or NSTIFFFileType.
If you need to customize the NSSavePanel, look into accessory views: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/AppFileMgmt/Articles/ManagingAccessoryViews.html
其他提示
// Get the data into a bitmap.
[viewBarChart lockFocus];
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[viewBarChart bounds]];
[viewBarChart unlockFocus];
NSData *exportedData = [rep representationUsingType:NSJPEGFileType properties:nil];
NSSavePanel *savepanel = [NSSavePanel savePanel];
savepanel.title = @"Save chart";
[savepanel setAllowedFileTypes:[NSArray arrayWithObject:@"jpg"]];
[savepanel beginSheetModalForWindow:self.view.window completionHandler:^(NSInteger result)
{
if (NSFileHandlingPanelOKButton == result)
{
NSURL* fileURL = [savepanel URL];
if ([fileURL.pathExtension isEqualToString:@""])
fileURL = [fileURL URLByAppendingPathExtension:@"jpg"];
[exportedData writeToURL:fileURL atomically:YES];
}
[rep release];
}];
不隶属于 StackOverflow