Saving an NSView to a png file?

后端 未结 2 2205
南笙
南笙 2020-12-15 01:16

I am making a simple program that creates game cards for a game I play. I have sent it out to some friends of mine for testing, but they really want it to save images, not j

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 02:13

    // 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];
     }];
    

提交回复
热议问题