我在下面的CGContextClearRect(c, self.view.bounds)
行上收到错误EXC_BAD_ACCESS。我似乎不知道为什么。这在UIViewController类中。这是崩溃期间我所使用的功能。
- (void)level0Func {
printf("level0Func\n");
frameStart = [NSDate date];
UIImage *img;
CGContextRef c = startContext(self.view.bounds.size);
printf("address of context: %x\n", c);
/* drawing/updating code */ {
CGContextClearRect(c, self.view.bounds); // crash occurs here
CGContextSetFillColorWithColor(c, [UIColor greenColor].CGColor);
CGContextFillRect(c, self.view.bounds);
CGImageRef cgImg = CGBitmapContextCreateImage(c);
img = [UIImage imageWithCGImage:cgImg]; // this sets the image to be passed to the view for drawing
// CGImageRelease(cgImg);
}
endContext(c);
}
这是我的startContext()和endContext():
CGContextRef createContext(int width, int height) {
CGContextRef r = NULL;
CGColorSpaceRef colorSpace;
void *bitmapData;
int byteCount;
int bytesPerRow;
bytesPerRow = width * 4;
byteCount = width * height;
colorSpace = CGColorSpaceCreateDeviceRGB();
printf("allocating %i bytes for bitmap data\n", byteCount);
bitmapData = malloc(byteCount);
if (bitmapData == NULL) {
fprintf(stderr, "could not allocate memory when creating context");
//free(bitmapData);
CGColorSpaceRelease(colorSpace);
return NULL;
}
r = CGBitmapContextCreate(bitmapData, width, height, 8, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
return r;
}
CGContextRef startContext(CGSize size) {
CGContextRef r = createContext(size.width, size.height);
// UIGraphicsPushContext(r); wait a second, we dont need to push anything b/c we can draw to an offscreen context
return r;
}
void endContext(CGContextRef c) {
free(CGBitmapContextGetData(c));
CGContextRelease(c);
}
我基本上想做的是绘制一个没有推送到堆栈的上下文,以便可以从中创建UIImage。这是我的输出:
wait_fences: failed to receive reply: 10004003
level0Func
allocating 153600 bytes for bitmap data
address of context: 68a7ce0
任何帮助,将不胜感激。我感到难过。
最佳答案
您没有分配足够的内存。以下是代码中的相关行:
bytesPerRow = width * 4;
byteCount = width * height;
bitmapData = malloc(byteCount);
计算
bytesPerRow
时,(正确)将宽度乘以4,因为每个像素需要4个字节。但是,当您计算byteCount
时,您不会乘以4,因此您的行为就像每个像素只需要1个字节一样。更改为此:
bytesPerRow = width * 4;
byteCount = bytesPerRow * height;
bitmapData = malloc(byteCount);
或者,不要分配任何内存,Quartz会为您分配正确的数量,并为您释放它。只需将
NULL
作为CGBitmapContextCreate
的第一个参数传递:r = CGBitmapContextCreate(NULL, width, height, 8, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
关于iphone - CGContextClearRect上的访问错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8673172/