关于图片截取时的内存泄露问题

心砚thu 2010-08-04 06:37:57
-(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上从一张图片上截取部分图片?谢谢啦~
...全文
475 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhangmo5629 2012-12-18
  • 打赏
  • 举报
回复
用CGImageRefRelease();
乌龟盖瑞 2010-09-01
  • 打赏
  • 举报
回复
请问你换用的什么方法?我也有内存泄露的问题!谢谢!
心砚thu 2010-08-04
  • 打赏
  • 举报
回复
嗯,好的~谢谢~已经解决了,换了一个方法就不泄漏了。另外,问一下,build and analyze是什么?
云瑀 2010-08-04
  • 打赏
  • 举报
回复
UIImage的東西不建議使用imageXXXX等靜態函數產生
除了會被autorelease外,還會被放在catch中,如果記憶體量過低,也會被釋放
建議您換利用alloc自行配置吧....
另外是否要嘗試看看Build And Analyze
心砚thu 2010-08-04
  • 打赏
  • 举报
回复
谢谢您的回复~~
是的,addObject会增加,但是我在[imageArray removeAllObjects];中已经把上次增加的释放掉了。我尝试过把他释放但是会出错,主要是因为subImage不是我分配的,所以应该是系统autorelease,不由我释放。您觉得呢?
云瑀 2010-08-04
  • 打赏
  • 举报
回复

[imageArray addObject:subImage];
NSLog(@"subImage retainCount=%d",[subImage retainCount]);

我沒執行您的程式,不過照之前經驗看問題應該出在這
您可以把subImage的retainCount印出
您的imageArray應該是NSMutableArray或NSArray?
addObject我記得會增加retainCount

[imageArray addObject:subImage];
[subImage release];

所以這樣應該可以解決您的問題

29,029

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧