如果 CGImageCreate 的数据提供者使用应用程序创建的数组,那么正确的调用会是什么样子?

2024-04-02

我试图在内存中创建一个位图,作为 drawLayer:inContext: 方法(此方法是 CALayer 委托协议的一部分)将调用的模式函数的一部分。模式函数看起来与此类似:

static const size_t kComponentsPerPixel = 4;
static const size_t kBitsPerComponent = sizeof(unsigned char) * 8;

NSInteger layerHeight = 160;
NSInteger layerWidth = 160;
CGContextSaveGState(context); 

CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();

size_t bufferLength = layerWidth * layerHeight * kComponentsPerPixel;

unsigned char *buffer = malloc(bufferLength);

// The real function does something more interesting with the buffer, but I cut it 
// to reduce the complexity while I figure out the crash.
for (NSInteger i = 0; i < bufferLength; ++i)
{
    buffer[i] = 255;
}
//memset(buffer, 255, bufferLength);

CGDataProviderRef provider = 
CGDataProviderCreateWithData(NULL, &buffer, bufferLength, NULL);//freeBitmapBuffer);

CGImageRef imageRef = 
CGImageCreate(layerWidth, layerHeight, kBitsPerComponent, 
              kBitsPerComponent * kComponentsPerPixel, 
              kComponentsPerPixel * layerWidth, 
              rgb, 
              kCGBitmapByteOrderDefault | kCGImageAlphaLast, 
              provider, NULL, false, kCGRenderingIntentDefault);

CGContextDrawImage(context, CGRectMake(0, 0, 160, 160), imageRef);

CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(rgb);     

CGContextRestoreGState(context);

后来,当drawLayer:inContext:调用CGContextFillRect来显示此函数创建的图案时,我得到EXC_BAD_ACCESS。堆栈顶部是 CGSConvertAlphaByte。我当时查看了缓冲区的内存,它看起来很好 - 设置为调用模式函数时设置的值。

我想也许我弄乱了 CGImageCreate 的一些参数,很可能是标志。或者缓冲区未按正确的顺序填充,但我不确定如果我用相同的值填充每个字节,我会出错。

有没有类似代码不会崩溃的想法或示例?


好的,苹果开发论坛发现了这个错误:由于某种原因我传递了 &buffer 而不是 buffer。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果 CGImageCreate 的数据提供者使用应用程序创建的数组,那么正确的调用会是什么样子? 的相关文章

随机推荐