4

我需要从 NSImage 获取 CGIImageRef。在 Cocoa for Mac OS X 中是否有一种简单的方法可以做到这一点?

4

2 回答 2

15

很难错过:

-[NSImage CGImageForProposedRect:context:hints:]

于 2009-11-11T01:36:41.717 回答
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;
}

如果您的图像来自文件,您最好使用图像源将数据直接加载到 CGImageRef 中。

于 2009-11-11T15:00:54.913 回答