【问题标题】:Saving an NSView to a png file?将 NSView 保存为 png 文件?
【发布时间】:2011-03-30 19:40:17
【问题描述】:

我正在制作一个简单的程序,为我玩的游戏创建游戏卡。我已经将它发送给我的一些朋友进行测试,但他们真的希望它能够保存图像,而不仅仅是打印它们。我试图让它保存为 .png 文件。我必须在这里提问。

  • 如何让它将我的视图保存为 .png 文件,包括视图的所有 NSImageWells。

  • 如何将 NSPopupButton 添加到 NSSavePanel 以允许用户选择格式?

非常感谢任何帮助。

【问题讨论】:

    标签: objective-c nsview nssavepanel


    【解决方案1】:

    首先为您的视图创建一个 TIFF 表示:

    // Get the data into a bitmap.
    [self lockFocus];
    rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[self bounds]];
    [self unlockFocus];
    data = [rep TIFFRepresentation];
    

    要支持多种文件类型,请使用:

    data = [rep representationUsingType:(NSBitmapImageFileType)storageType
    properties:(NSDictionary *)properties];
    

    NSBitmapImageFileType 是一个枚举常量,指定位图图像的文件类型。它可以是 NSBMPFileType、NSGIFFileType、NSJPEGFileType、NSPNGFileType 或 NSTIFFFileType。

    如果您需要自定义 NSSavePanel,请查看附件视图:http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/AppFileMgmt/Articles/ManagingAccessoryViews.html

    【讨论】:

    • 编辑:哎呀,再读一遍。没想到你已经涵盖了。过会儿会删掉。
    • -[NSData writeToFile:(NSString *)path atomically:(BOOL)flag] 会很有趣。
    • 好的。我通过添加以下代码使其工作:[data writeToFile:[savePanel filename] atomically:YES];。这个想法来自这个this 网站。
    【解决方案2】:
    // 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];
     }];
    

    【讨论】: