我在下面的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
任何帮助将不胜感激。我很难过。
答案 0 :(得分:4)
你没有分配足够的内存。以下是代码中的相关行:
bytesPerRow = width * 4;
byteCount = width * height;
bitmapData = malloc(byteCount);
当你计算bytesPerRow
时,你(正确地)将宽度乘以4,因为每个像素需要4个字节。但是当你计算byteCount
时,你不乘以4,所以你就像每个像素只需要1个字节一样。
将其更改为:
bytesPerRow = width * 4;
byteCount = bytesPerRow * height;
bitmapData = malloc(byteCount);
OR ,不要分配任何内存,Quartz会为您分配正确的金额,并为您释放。只需将NULL
作为CGBitmapContextCreate
的第一个参数传递:
r = CGBitmapContextCreate(NULL, width, height, 8, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
答案 1 :(得分:0)
检查self.view.bounds.size的值是否有效。可以在正确设置视图大小之前调用此方法。