views:

135

answers:

1

I have a collection of objects which describe an image-name, its size and it's X/Y location. The collection is sorted by "layers", so I can composite the images in a sort of painter's algorithm.

From this, I can determine the rectangle necessary to hold all of the images, so now what I want to do is:

  • Create some sort of buffer to hold the result (The NS equivalent of what iPhoneOS calls UIGraphicsContext.)
  • Draw all the images into the buffer.
  • Snag a new NSImage out of the composited result of the buffer.

In iPhoneOS, this is the code that does what I want:

UIGraphicsBeginImageContext (woSize);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor clearColor] set];
    CGContextFillRect(ctx, NSMakeRect(0, 0, woSize.width, woSize.height));
    // draw my various images, here.
    // i.e. Various repetitions of [myImage drawAtPoint:somePoint];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

What I'm looking for is how to do that in Desktop Cocoa/NS.

Thanks!

+3  A: 
NSImage* resultImage = [[[NSImage alloc] initWithSize:imageSize] autorelease];
[resultImage lockFocus];

[anotherImage drawAtPoint:aPoint fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
// Or any of the other about 6 options; see Apple's guide to pick.

[resultImage unlockFocus];

Check Apple's Drawing Guide for a much longer, more detailed answer.

andyvn22
Docs say Deprecated in Snow-Leopard."Important: If you are writing new code, or updating old code, you should avoid using this method. Instead, you should use the drawAtPoint:fromRect:operation:fraction: or drawInRect:fromRect:operation:fraction: method to draw the image. Although the method itself is not deprecated, the behavior it provides is not recommended for general use."But I'll try drawAtPoint and, if it works, give you the correct answer checkmark. (You might want to edit your answer.)Thanks!
Olie
Good call. Edited. The reason, I assume, is that draw checks the source rect and composite doesn't. This is fine as long as you're sure you're passing a sensible rect (and it's a little faster, too) but it is indeed safer to use draw.
andyvn22
Yeah, lockFocus was the thing I was missing (such an intuitive name, I can't imagine HOW I didn't think to check the docs for that! ;)Thanks!
Olie