Estoy tratando de crear un mapa de bits en memoria como parte de una función de patrón que llamará un método drawLayer: inContext: (este método es parte del protocolo delegado CALayer). La función de patrón es similar a esto:¿Cómo se ve una llamada correcta a CGImageCreate si el proveedor de datos utiliza una matriz creada por la aplicación?
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);
Más tarde, cuando drawLayer: InContext: llama CGContextFillRect para visualizar el patrón creado por esta función, me sale EXC_BAD_ACCESS. La parte superior de la pila es CGSConvertAlphaByte. Miré la memoria del búfer en ese momento, y parecía estar bien ajustado a exactamente lo que estaba configurado cuando se llamó a la función de patrón.
Creo que tal vez he estropeado algún parámetro de CGImageCreate, muy posiblemente las banderas. O el búfer no está lleno en el orden correcto, pero no estoy seguro de cómo puedo equivocarme si llenero cada byte con el mismo valor.
¿Alguna idea o ejemplo de código similar que no se cuelgue?