2011-12-29 2 views
2

아래의 CGContextClearRect(c, self.view.bounds) 행에 EXC_BAD_ACCESS 오류가 표시됩니다. 나는 이유를 알 수없는 것 같습니다. 이것은 UIViewController 클래스에 있습니다. 다음은 내가 충돌하는 동안의 기능입니다.CGContextClearRect에 대한 액세스가 잘못되었습니다.

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

내가 기본적으로 내가 스택에 밀어 있지 않다 컨텍스트에 그려지고 노력하고 있어요 그래서 나는를 만들 수 있습니다 여기에

- (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()이다 그것으로 UIImage. 여기에 내 결과입니다 :

wait_fences: failed to receive reply: 10004003 
level0Func 
allocating 153600 bytes for bitmap data 
address of context: 68a7ce0 

도움이 되길 바랍니다. 나는 곤두박질 친다.

답변

4

충분한 메모리를 할당하지 않았습니다. 각 픽셀은 4 바이트가 필요하기 때문에

bytesPerRow = width * 4; 
byteCount = width * height; 
bitmapData = malloc(byteCount); 

당신이 bytesPerRow을 계산

, 당신은 (제대로) 4 폭을 곱 : 다음 코드에서 해당 라인입니다. 그러나 byteCount을 계산할 때 이 아니라이 4를 곱하면 각 픽셀에 1 바이트 만 필요한 것처럼 작동합니다. 이것에

변경이 : 당신을 위해 그것을

bytesPerRow = width * 4; 
byteCount = bytesPerRow * height; 
bitmapData = malloc(byteCount); 

또는는 어떤 메모리를 할당하지 않고 석영은 당신을 위해 올바른 금액을 할당합니다, 무료. 그냥 CGBitmapContextCreate의 첫 번째 인수로 NULL을 전달합니다

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

내가 너없이 무엇을 할 수 있니? – Relish

0

self.view.bounds.size 값이 올바른지 확인하십시오. 이 메서드는 뷰 크기가 올바르게 설정되기 전에 호출 될 수 있습니다.

+0

는 그 처음에 너무 생각하지만 유효 었죠 및 강탈 내가 잘못하고 있었는지 발견했다. – Relish

관련 문제