简体   繁体   English

如何从CGContextRef获取CGImageRef?

[英]How to get CGImageRef from CGContextRef?

I am trying to add two images into context, however it does not work and throws 我正在尝试将两个图像添加到上下文中,但是它不起作用并抛出

GBitmapContextCreateImage: invalid context 0x0 GBitmapContextCreateImage:无效上下文0x0

error. 错误。 I use the following code: 我使用以下代码:

//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);

this seems fine but the resulting images are all black or look very similar to this: 这看起来不错,但是生成的图像全是黑色或看起来与此非常相似: 形象不佳

What should be changed in the code? 代码中应更改什么? Thanks in advance! 提前致谢!

kCGBitmapAlphaInfoMask is not a valid value for the last ( bitmapInfo ) argument to CGBitmapContextCreate . kCGBitmapAlphaInfoMask的最后一个( bitmapInfo )参数, CGBitmapContextCreate It is a mask (hence the name) you can use with the & operator to get just the CGImageAlphaInfo out of a CGBitmapInfo value. 这是一个面具(因此得名),您可以与使用&运营商得到公正的CGImageAlphaInfo出的CGBitmapInfo值。 You would never pass kCGBitmapAlphaInfoMask where a CGBitmapInfo or CGImageAlphaInfo is expected. 您永远不会在期望CGBitmapInfoCGImageAlphaInfo地方传递kCGBitmapAlphaInfoMask

Assuming you don't need a specific byte order, I believe this is the highest performance pixel format with alpha channel on iOS: 假设您不需要特定的字节顺序,那么我相信这是iOS上具有Alpha通道的性能最高的像素格式:

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

And this should be the highest performance without alpha channel: 而这应该是没有alpha通道的最高性能:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM