0

I want to take my NSView(With layers) as an image can I do so in OSX ?

in iOS I would do the following

-(UIImage*) makeImage//snapshot the view
{
    UIGraphicsBeginImageContext(self.view.bounds.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;
}

I tried this solution from 1 of the SO answers

[[NSImage alloc] initWithData:[view dataWithPDFInsideRect:[view bounds]]];

but it didn't work because I have layers in my NSView.

I started from converting UI to NS and now I have warnings on every line :)

-(NSImage*) makeImage :(RMBlurredView*)view
{
    UIGraphicsBeginImageContext(view.bounds.size);

    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];

    NSImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return viewImage;
}

I am not familiar with OSX can some 1 help me to convert this code to OSX ?

Coldsteel48
  • 3,482
  • 4
  • 26
  • 43

1 Answers1

5

drawing to the image is tad different than in iOS:

  1. you create a blank image, LOCK on to it, so all drawing goes to that graphics context

    NSImage *image = [[NSImage alloc] initWithSize:self.view.bounds.size];
    [image lockFocus];
    
  2. you draw your layer same as on iOS

    CGContextRef ctx = [NSGraphicsContext currentContext].graphicsPort;
    [self.view.layer renderInContext:ctx];
    
  3. unlock image

    [image unlockFocus];
    

NOTE this is only if your view is layered. it doesn't work for non-layered views!
your view -as shown above- is layer backed so all's fine ;)

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
  • Thank you very much :) -BTW it is my route to handle the previous question , I couldn't find how to make gif through out the layered view , so i decided to draw all its static conents and then to take this snapShot and add it as regular nsview with apicture inside :) – Coldsteel48 Jun 01 '14 at 10:56
  • I answered this today :) you have to set imageView.canDrawSubviewsInLayer = YES so animated gifs work. see: http://stackoverflow.com/questions/23969667/how-to-display-animated-gif-in-objective-c-on-top-of-the-layered-view/23969766#23969766 – Daij-Djan Jun 01 '14 at 10:58
  • However I feel sad with this solution , but it works like a charm :) – Coldsteel48 Jun 01 '14 at 10:58
  • Oh I didnt see that -> didn't recieve anything from SO about your update , I am trying it now I hope it will work :)) Thanks you :) – Coldsteel48 Jun 01 '14 at 11:00