2009-11-11 51 views

回答

5

如果你需要瞄準的Mac OS X 10.5或任何其他以前的版本,使用下面的代碼片段來代替。如果你不這樣做,NSD的答案是正確的選擇。

CGImageRef CGImageCreateWithNSImage(NSImage *image) { 
    NSSize imageSize = [image size]; 

    CGContextRef bitmapContext = CGBitmapContextCreate(NULL, imageSize.width, imageSize.height, 8, 0, [[NSColorSpace genericRGBColorSpace] CGColorSpace], kCGBitmapByteOrder32Host|kCGImageAlphaPremultipliedFirst); 

    [NSGraphicsContext saveGraphicsState]; 
    [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:bitmapContext flipped:NO]]; 
    [image drawInRect:NSMakeRect(0, 0, imageSize.width, imageSize.height) fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0]; 
    [NSGraphicsContext restoreGraphicsState]; 

    CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext); 
    CGContextRelease(bitmapContext); 
    return cgImage; 
} 

如果你的圖片來自於一個文件,你可以使用image source直接加載數據到一個CGImageRef會更好。

+0

我做了類似於這個的使用來自bitmapContext的數據。一個重要的問題:如果你想使用上下文中的數據,你需要在NSGraphicsContext上調用flushGraphics。沒有它,它在調試模式下工作正常,但在發佈模式下分段。 – Sam 2013-09-12 11:49:40