将NSImage*转换为CGImageRef?

Bri*_*tow 15 cocoa core-graphics objective-c nsimage cgimage

有一种简单的方法可以在10.5中运行吗?

在10.6中,我可以使用nsImage CGImageForProposedRect:NULL上下文:NULL提示:NULL

如果我不使用1b黑白图像(如Group 4 TIFF),我可以使用位图,但cgbitmaps似乎不喜欢这种设置...有没有一般的方法这样做?

我需要这样做,因为我有一个看似只想添加CGImages的IKImageView,但我所拥有的只是NSImages.目前,我正在使用一个私有的setImage:(NSImage*)方法,我真的不会使用...

phe*_*cks 30

此页面上找到以下解决方案:

NSImage* someImage;
// create the image somehow, load from file, draw into it...
CGImageSourceRef source;

source = CGImageSourceCreateWithData((CFDataRef)[someImage TIFFRepresentation], NULL);
CGImageRef maskRef =  CGImageSourceCreateImageAtIndex(source, 0, NULL);
Run Code Online (Sandbox Code Playgroud)

所有方法似乎都是10.4+所以你应该没问题.

  • 是的,但不要称"TIFFRepresentation"数百次.根据`NSImage`,它最终可以在内存中创建完整的,未压缩的图像数据副本. (7认同)
  • 与Peter的解决方案相比,这对性能和可预测性都不太好.如果图像有多种表示形式(例如16x16版本和128x128版本),您会这样做吗?未定义. (2认同)

Pet*_*sey 17

[这是很长的路要走.如果您仍然支持旧版本的OS X,则应该只执行此操作.如果您需要10.6或更高版本,请改用该CGImage方法.

  1. 创建CGBitmapContext.
  2. 为位图上下文创建NSGraphicsContext.
  3. 将图形上下文设置为当前上下文.
  4. 画出图像.
  5. 从位图上下文的内容创建CGImage.
  6. 释放位图上下文.

  • 彼得,你是我在这里羡慕和信任的成员.感谢您分享的所有知识和经验,以及您提供的全面知识. (3认同)

Pet*_*sey 16

从Snow Leopard开始,您可以通过向NSImage发送消息,让图像为您创建CGImageCGImageForProposedRect:context:hints:.


Kan*_*ire 14

以下是使用的更详细的答案- CGImageForProposedRect:context:hints::

NSImage *image = [NSImage imageNamed:@"image.jpg"];

NSRect imageRect = NSMakeRect(0, 0, image.size.width, image.size.height);

CGImageRef cgImage = [image CGImageForProposedRect:&imageRect context:NULL hints:nil];
Run Code Online (Sandbox Code Playgroud)