当前位置:编程学习 > wap >>

cocos2d中CCSprite的使用总结

一、精灵创建及初始化

1、从图片文件创建:

[cpp]
CCSprite *sprite = [CCSprite spriteWithFile:@"Icon.png"]; 
2、从帧缓存创建:

[cpp]
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"MineSweeping.plist"]; 
CCSprite *sprite = [CCSprite spriteWithSpriteFrameName:@"Icon.png"]; 
3、初始化及自定义大小

[cpp]
CCSprite *sprite = [CCSprite spriteWithFile:@"Icon.png" rect:CGRectMake(x,y,w,h)]; 
备注:默认锚点ccp(0.5,0.5),默认位置 ccp(0,0),contentSize为精灵图片尺寸

二、精灵常用属性及方法:

[cpp] 
[self addChild:sprite]; //添加入层中,self为CCLayer   
sprite.scale=2;//放大2倍,参数为比例,1保持不变,0.5代表50%,2代表200%   
sprite.rotation=90;//旋转90度    
sprite.opacity=255;//设置透明度为完全不透明(范围0~255) 
sprite.anchorPoint=ccp(0,0);//设置锚点为左下角,默认为ccp(0.5,0.5)中心点 
sprite.position=ccp(100,100);//设置精灵左下角坐标是x=100,y=100,本地GL坐标系   
[sprite setFlipX:YES];//X轴镜像反转    
[sprite setFlipY:YES];//Y轴镜像反转  
[sprite setVisible:NO];//设置隐藏,默认为可见  
[sprite setColor:ccc3(255, 0, 0)];//设置颜色为红色,三原色 
[sprite zOrder]; //精灵层叠次序即Z轴(小的在下面,大的在上面),注意这是只读属性,不能通过sprite.zOrder=2实现Z轴重设   
[sprite setTextureRect:CGRectMake(10, 10, 30, 30)];//起始点坐标(做上角坐标系),宽高   
三、添加其他精灵

CCSprite继承自CCNode,所以你可以对它进行addChild的操作:

[cpp
CCSprite *s1 = [CCSprite spriteWithFile:@"Icon.png"]; 
CCSprite *s2 = [CCSprite spriteWithFile:@"Icon.png"]; 
[s1 addChild:s2]; 
四、精灵Z轴重设

[cpp] 
[self reorderChild:sprite z:10];//self为CCLayer 
五、精灵换图

1、直接利用新建贴图进行更换
[cpp]
//更换贴图    
CCTexture2D * texture =[[CCTextureCache sharedTextureCache] addImage: @"Default.png"];//新建贴图    
[sprite setTexture:texture];  
2、利用帧替换

[cpp] 
//加载帧缓存  
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"MineSweeping.plist"];     
//从帧缓存中取出Default.png 
CCSpriteFrame* frame2 = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"Default.png"];    
[sprite setDisplayFrame:frame2]; 
  


作者:wangqiuyun
补充:移动开发 , 其他 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,