-(void)readPicture{
UIImage *image;
switch (roleType) {
case ROLE_PLAYER:
image=[UIImage imageNamed:@"man.png"];
break;
default:
break;
}

int subImageLocationX;
if (direction.x==-1&&direction.y==0) {
subImageLocationX=0;
}else if (direction.x==1&&direction.y==0) {
subImageLocationX=IMAGE_SIZE;
}else if (direction.x==0&&direction.y==1) {
subImageLocationX=IMAGE_SIZE*2;
}else if (direction.x==0&&direction.y==-1) {
subImageLocationX=IMAGE_SIZE*3;
}else if (direction.x==-1&&direction.y==1) {
subImageLocationX=IMAGE_SIZE*4;
}else if (direction.x==1&&direction.y==-1) {
subImageLocationX=IMAGE_SIZE*5;
}else if (direction.x==1&&direction.y==1) {
subImageLocationX=IMAGE_SIZE*6;
}else if (direction.x==-1&&direction.y==-1) {
subImageLocationX=IMAGE_SIZE*7;
}



[imageArray removeAllObjects];
for (int i=0; i<14; i++) {
CGRect subImageRect=CGRectMake(subImageLocationX, i*IMAGE_SIZE, IMAGE_SIZE, IMAGE_SIZE);
CGImageRef imageRef=image.CGImage;
CGImageRef subImageRef=CGImageCreateWithImageInRect(imageRef, subImageRect);
UIGraphicsBeginImageContext(CGSizeMake(IMAGE_SIZE, IMAGE_SIZE));
CGContextRef context=UIGraphicsGetCurrentContext();
CGContextDrawImage(context, subImageRect, subImageRef);
UIImage *subImage=[UIImage imageWithCGImage:subImageRef];
UIGraphicsEndImageContext();
[imageArray addObject:subImage];
}



[imageView setImage:[imageArray objectAtIndex:0]];
}
这是我从一张大图上截取部分图片时的代码,但在模拟器上运行时每次调用readPicture都会分配大量的内存,用leaks查泄露时提示CGImage和CGDataProvider造成泄露,定位的语句是UIImage *subImage=[UIImage imageWithCGImage:subImageRef];造成泄露,但这是由系统负责分配的内存,我又无法释放。我尝试使用autoreleasepool来释放,但也没有用。能不能麻烦各位帮看一下,或者大家有没有其他办法在iphone上从一张图片上截取部分图片?谢谢啦~

解决方案 »

  1.   


    [imageArray addObject:subImage];
    NSLog(@"subImage retainCount=%d",[subImage retainCount]);我沒執行您的程式,不過照之前經驗看問題應該出在這
    您可以把subImage的retainCount印出
    您的imageArray應該是NSMutableArray或NSArray?
    addObject我記得會增加retainCount[imageArray addObject:subImage];
    [subImage release];所以這樣應該可以解決您的問題
      

  2.   

    谢谢您的回复~~
    是的,addObject会增加,但是我在[imageArray removeAllObjects];中已经把上次增加的释放掉了。我尝试过把他释放但是会出错,主要是因为subImage不是我分配的,所以应该是系统autorelease,不由我释放。您觉得呢?
      

  3.   

    UIImage的東西不建議使用imageXXXX等靜態函數產生
    除了會被autorelease外,還會被放在catch中,如果記憶體量過低,也會被釋放
    建議您換利用alloc自行配置吧....
    另外是否要嘗試看看Build And Analyze
      

  4.   

    嗯,好的~谢谢~已经解决了,换了一个方法就不泄漏了。另外,问一下,build and analyze是什么?