Saving an NSView to a png file?

本小妞迷上赌 提交于 2019-11-28 22:02:46

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];
 }];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!