Is there any way to Convert NSView Contain many Subviews with background color into NSImage ? Sample code will be great
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];
}
}];
i also used the following code to
[_collageView lockFocus];
NSBitmapImageRep *bits = [[NSBitmapImageRep alloc]initWithFocusedViewRect: [_collageView bounds]];
[_collageView unlockFocus];
NSImage *image1 = [[NSImage alloc] init];
[image1 addRepresentation: bits];
[self.ImageView setImage:image1];
but not working
I am able to solve my problem with the following Code
// Setup the image to render
NSRect imgRect = _collageView.frame;
NSSize imgSize = imgRect.size;
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
pixelsWide:imgSize.width
pixelsHigh:imgSize.height
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSDeviceRGBColorSpace
bitmapFormat:NSAlphaFirstBitmapFormat
bytesPerRow:0
bitsPerPixel:0];
NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:rep];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:context];
// Render
CGContextRef zCgContextRef = (CGContextRef) [context graphicsPort];
[[_collageView layer] renderInContext:zCgContextRef];
// Get the Data for the image
NSData *exportedData = [rep representationUsingType:NSJPEGFileType properties:nil];
// Start the savepanel
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];
}
}];