Search code examples
cocoansviewdrawrectnsimageimage-capture

Rendering NSView to image: cacheDisplayInRect draws transparent areas differently from usual drawRect call


Greetings! I have a problem and Googling brought no results...

I implemented the drawRect method for my NSView (subclass) to draw some shadows and semi-transparent fills. Everything looks great! But now I need to create an NSImage from my NSView (make snapshot) for drag&drop purposes.

It works, but draws in some different manner: darker and not so contrast as should be.
Why? Maybe because of NSGraphicContext different options? Need help and/or advice!

Here is the code for getting NSImage from NSView:

- (NSImage *)makeImageSnapshot {

    NSSize imgSize = self.bounds.size;

    NSBitmapImageRep * bir = [self bitmapImageRepForCachingDisplayInRect:[self bounds]];
    [bir setSize:imgSize];

    [self cacheDisplayInRect:[self bounds] toBitmapImageRep:bir];

    NSImage* image = [[[NSImage alloc] initWithSize:imgSize] autorelease];
    [image addRepresentation:bir];

    return image;
}

And here are the images to compare visually:

  1. Normal - drawn by drawRect usual call: http://cl.ly/image/213C1Y1V0v2H
  2. Bad - captured into NSImage: http://cl.ly/image/183q442S2J14

Thought the difference might seem very small, believe me - it is obvious while working with application. I don't undertand why that is happening. And hope someone can help...

Thanks in advance!


Solution

  • I believe the transparency problem is caused by not having other things to blend it against when it's cached on its own.

    Try -dataWithPDFInsideRect: or -dataWithEPSInsideRect: and get your image reps from there.