Fork me on GitHub

Cocos2d加载图片的方式

http://wangzy-boy.iteye.com/blog/907141

分享一个我用cocos2d加载图片的方式,其实很简单,我觉得还挺实用的

首先要提醒一点,ihpone开发中所有的图片最好都是png格式的,虽然png格式的图片比jpg或其他的图片要大,但是png的图片在sdk中是做过优化处理的,是苹果推荐的格式,对这个格式支持也是相对好的.尤其是在最新4.2sdk,如果你有jpg的图片,并且比较大,在真机上是现实不出来的.

 

最开始做项目,cocos2d了解的比较少,添加一个CCSprite,为了简单,就直接用

CCSprite *sprite = [CCSprite spriteWithFile:@"图片名称"];

如果你是这样用,那就是说图片要通过自动释放机制来完成对加载图片的释放了,那究竟什么时候图片会自动释放掉呢?当然是程序内存快要用尽的时候

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { 
[[CCTextureCache sharedTextureCache] removeUnusedTextures];
}

 

看你应用的delegate方法,会有上面一个函数,这个函数就是用来触发什么释放图片的.内存快要到达极限的时候会发出警告告诉上边的方面,然后这个方法就会从cache中释放掉当前不用的图片,

 

removeUnusedTextures进到这个里面会看到实际上就是释放掉retaincount=1的资源.通过log会发现内存警告是分级别的,

 

当时1级的时候问题不大,2级的时候就危险了,超过2级程序就完蛋了.而在调用内存警告之前,通过xcode提供内存跟踪工具,会发现图片一直会占着内存.

 

 

 

所以就不要依赖自动释放了,会害了项目的,尤其做游戏,图片比较多,如果用这种方式加载素材,到后期就惨了.我是深有体会.

 

 

 

我是这样做的

 

 

CCTexture2D * backBGTexture = [[CCTextureCache sharedTextureCache] addImage:@"a_aboutBG.png"]; 
CCSprite * backgroundSprite = [[CCSprite alloc] initWithTexture:m_backBGTexture];
[self addChild:backgroundSprite];
[backgroundSprite release];

其实就是手动构建CCsprite这样,在图片不用的时候(一般在dealloc方法中),直接把图片remove掉

-(void)dealloc 
{
[[CCTextureCache sharedTextureCache] removeTexture:backBGTexture];
[super dealloc];
}

 

再通过内存跟踪工具会发现,内存当即被释放掉了.这样场景间切换的时候,就可以把上一个场景的图片全部释放掉.

 

我就是这样做的.呵呵.

 

 

 

 

    

 

    CCSpriteFrameCache* frameCache = [CCSpriteFrameCache sharedSpriteFrameCache];

 

     [frameCache addSpriteFramesWithFile:@"advShelfUpLevel.plist"];

 

    

 

    CCSpriteFrame *frame  = [frameCache spriteFrameByName:@"bomb_effect_13_15.png"];

 

    CCSprite *sp = [CCSprite spriteWithSpriteFrame:frame];

 

    CCTexture2D *tex = [[CCTextureCache sharedTextureCache] addImage:<#(NSString *)#>]

释放:

 

    [[CCTextureCache sharedTextureCache] removeTexture:tex];

 

     [[CCSpriteFrameCache sharedSpriteFrameCache] removeSpriteFramesFromTexture:tex];

 

   //[[CCSpriteFrameCache sharedSpriteFrameCache] removeSpriteFramesFromFile:<#(NSString *)#>];

 

posted on 2012-04-07 18:36  pengyingh  阅读(4496)  评论(0)    收藏  举报

导航