2011-12-29 65 views
2

我在下面的行CGContextClearRect(c, self.view.bounds)上收到錯誤EXC_BAD_ACCESS。我似乎無法弄清楚爲什麼。這是在UIViewController類中。這是我在碰撞期間的功能。對CGContextClearRect的訪問不正確

- (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 

任何幫助,將不勝感激。我很難過。

回答

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將分配正確的金額給你,並釋放它。只是通過NULLCGBitmapContextCreate第一個參數:

r = CGBitmapContextCreate(NULL, width, height, 8, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast); 
+0

沒有你,我會做什麼? – Relish 2011-12-29 20:55:24

0

檢查self.view.bounds.size的值是否有效。在正確設置視圖大小之前,可以調用此方法。

+0

我認爲首先太多,但它最終是有效的,搶發現我在做什麼錯。 – Relish 2011-12-29 20:58:33