ios - 如何从CGContextRef获取CGImageRef?

标签 ios objective-c iphone xcode core-foundation

我试图将两个图像添加到上下文中,但它不起作用并抛出

GBitmapContextCreateImage: invalid context 0x0

错误。我使用以下代码:

//some image
CGImageRef image = ...
//some image as well, but masked. Works perfectly.
CGImageRef blurredAndMasked = CGImageCreateWithMask(blurred, mask);
//Both images are fine. Sure.

//Initializing the context and color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(nil, frameSize.width, frameSize.height, 8, 0, colorSpace, kCGBitmapAlphaInfoMask);

//Drawing images into the context
CGContextDrawImage(ctx, CGRectMake(0, 0, frameSize.width, frameSize.height), image);
CGContextDrawImage(ctx, CGRectMake(0, 0, frameSize.width, frameSize.height), blurredAndMasked);

//getting the resulting image
CGImageRef ret = CGBitmapContextCreateImage(ctx);

//releasing the stuff
CGImageRelease(image);
CGImageRelease(blurred);
CGImageRelease(blurredAndMasked);
CGColorSpaceRelease(colorSpace);
CGContextRelease(ctx);

这看起来不错,但生成的图像全是黑色或看起来与此非常相似:Bad image

代码中应该更改什么?提前致谢!

最佳答案

kCGBitmapAlphaInfoMask 不是 CGBitmapContextCreate 的最后一个 (bitmapInfo) 参数的有效值。它是一个掩码(因此得名),您可以使用 & 运算符从 CGBitmapInfo 值中获取 CGImageAlphaInfo。您永远不会在需要 CGBitmapInfoCGImageAlphaInfo 的地方传递 kCGBitmapAlphaInfoMask

假设您不需要特定的字节顺序,我相信这是 iOS 上具有 alpha channel 的最高性能像素格式:

CGContextRef ctx = CGBitmapContextCreate(nil,
    frameSize.width, frameSize.height, 8, 0, colorSpace,
    kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);

这应该是没有 alpha channel 的最高性能:

CGContextRef ctx = CGBitmapContextCreate(nil,
    frameSize.width, frameSize.height, 8, 0, colorSpace,
    kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst);

关于ios - 如何从CGContextRef获取CGImageRef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31436468/

相关文章:

objective-c - 如何在运行时识别方法的返回类型?

iphone - 应用内购买 - 存储/获取用户购买历史记录 | iOS系统

iphone - 添加 subview - Monotouch

ios - 使用 Storyboard将 iAd 添加/集成到应用程序中

ios - 是否可以从 iphone 打开 apple watch 应用程序

ios - 添加 textView 作为 View 的 subview 并将此 View 添加到视频

ios - X代码 : Pod Update

ajax - 了解 AJAX 何时加载到 UIWebView

objective-c - 在 Objective-C (iPhone) 中从 Excel 文件中读取数据

objective-c - 运行应用程序时,如何在 Mac OS X Cocoa 应用程序中使用放入 Xcode 中的文件?