//
//  OxNSImage.m
//  AdventureEngine
//
//  Created by Nicholas Matsakis on 2/20/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "OxNSImage.h"


@implementation NSImage (Oaxaca2)

- (CGImageRef)CGImage
{
    CGFloat desiredPixelWidth = self.size.width;
    CGFloat desiredPixelHeight = self.size.height;
    
    CGContextRef bitmapCtx = CGBitmapContextCreate(NULL/*data - pass NULL to let CG allocate the memory*/, 
                                                   desiredPixelWidth,  
                                                   desiredPixelHeight, 
                                                   8 /*bitsPerComponent*/, 
                                                   0 /*bytesPerRow - CG will calculate it for you if it's allocating the data.  This might get padded out a bit for better alignment*/, 
                                                   [[NSColorSpace genericRGBColorSpace] CGColorSpace], 
                                                   kCGBitmapByteOrder32Host|kCGImageAlphaPremultipliedFirst);
    
    [NSGraphicsContext saveGraphicsState];
    [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:bitmapCtx flipped:NO]];
    [self drawInRect:NSMakeRect(0,0, desiredPixelWidth, desiredPixelHeight) fromRect:NSZeroRect/*sentinel, means "the whole thing*/ operation:NSCompositeCopy fraction:1.0];
    [NSGraphicsContext restoreGraphicsState];
    
    CGImageRef cgImage = CGBitmapContextCreateImage(bitmapCtx);
    CFRelease(bitmapCtx);    
    return cgImage;
}

@end
