What does a correct call to CGImageCreate look like if the data provider for it uses an array created by the app?

风格不统一 提交于 2019-12-06 19:31:31

问题


I'm trying to create a bitmap in memory as part of a pattern function that a drawLayer:inContext: method (this method is part of the CALayer delegate protocol) will call. The pattern function looks similar to this:

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

Later, when drawLayer:inContext: calls CGContextFillRect to display the pattern created by this function, I get EXC_BAD_ACCESS. The top of the stack is CGSConvertAlphaByte. I looked at the buffer's memory at that point, and it seemed fine - set to exactly what it was set to when the pattern function was called.

I think that maybe I messed up some parameter of CGImageCreate, quite possibly the flags. Or the buffer is not populated in the right order, but I'm not sure how I can go wrong if I fill every byte with the same value.

Any ideas or examples of similar code that is non-crashing?


回答1:


OK, so the Apple dev forums spotted the mistake: I was passing &buffer for some reason instead of buffer.



来源:https://stackoverflow.com/questions/7035250/what-does-a-correct-call-to-cgimagecreate-look-like-if-the-data-provider-for-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!