Cocoa: how to render an image?

I want to know if there is any way to render an image? like a screenshot, but I can specify any kind of this method. I know how to do this in ios. Saving view contents , but how to do it on mac os?

+6
source share
2 answers

There are several ways, but they do not work perfectly. Many issues are related to views supported by Layer Backed.

if you don’t have support for layers or hosting, you can use this code:

NSData* data = [mainView dataWithPDFInsideRect:[mainView bounds]]; NSImage *img = [[NSImage alloc] initWithData:data]; 

if you work with layer based views:

until 10.8 the best way for me was

  NSSize mySize = mapImage.bounds.size; NSSize imgSize = NSMakeSize( mySize.width, mySize.height ); NSBitmapImageRep *bir = [mapImage bitmapImageRepForCachingDisplayInRect:[mapImage bounds]]; [bir setSize:imgSize]; [mapImage cacheDisplayInRect:[mapImage bounds] toBitmapImageRep:bir]; caheImg = [[NSImage alloc]initWithSize:imgSize]; [caheImg addRepresentation:bir]; 

but in 10.8 bitmapImageRepForCachingDisplayInRect stopped working with layer-supported views.

it is possible to take a screenshot of your screen and cut your appearance:

 + (NSImage*) screenCacheImageForView:(NSView*)aView { NSRect originRect = [aView convertRect:[aView bounds] toView:[[aView window] contentView]]; NSRect rect = originRect; rect.origin.y = 0; rect.origin.x += [aView window].frame.origin.x; rect.origin.y += [[aView window] screen].frame.size.height - [aView window].frame.origin.y - [aView window].frame.size.height; rect.origin.y += [aView window].frame.size.height - originRect.origin.y - originRect.size.height; CGImageRef cgimg = CGWindowListCreateImage(rect, kCGWindowListOptionIncludingWindow, (CGWindowID)[[aView window] windowNumber], kCGWindowImageDefault); return [[NSImage alloc] initWithCGImage:cgimg size:[aView bounds].size]; } 
+14
source

I use this code in my application, which works great.

However, if I drag the application onto an additional monitor, the screen shot is thrown out and I get the rectangle not captured correctly.

The following code fixes this problem (I also removed some redundant mathematical calculations from the calculation where the field was subtracted and then added) if someone encounters this in the future:

 NSRect originRect = [aView convertRect:[aView bounds] toView:[[aView window] contentView]]; NSArray *screens = [NSScreen screens]; NSScreen *primaryScreen = [screens objectAtIndex:0]; NSRect rect = originRect; rect.origin.y = 0; rect.origin.x += [aView window].frame.origin.x; rect.origin.y = primaryScreen.frame.size.height - [aView window].frame.origin.y - originRect.origin.y - originRect.size.height; 
+2
source

Source: https://habr.com/ru/post/922804/


All Articles