CCSprite的使用方法

来源:互联网 发布:人工智能在医疗领域 编辑:程序博客网 时间:2024/06/07 10:17

CCSprite的使用方法大全

一、精灵创建及初始化

  • 从图片文件创建:
CCSprite *sprite = [CCSpritespriteWithFile:@"ImageFileName.png"]; 

默认锚点 ccp(0.5,0.5),
默认位置 ccp(0,0),
CCSprite尺寸(contentSize)为图片尺寸

  • 从帧缓存创建:
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"MineSweeping.plist"];  CCSprite *sprite = [CCSprite spriteWithSpriteFrameName:@"ImageFileName.png"];  
  • 初始化及自定义大小
CCSprite *sprite = [CCSprite spriteWithFile:@"ImageFileName.png" rect:CGRectMake(x,y,w,h)];  

只显示图片的一部分,大小为 w,h

iOS设备的贴图尺寸必须符合“2的n次方” 规定,所以贴图的宽和高必须是2,4,8,16,32,64,128,256,512,1024. 在第三代设备上可以达到2048像素

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

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

三、添加其他精灵

  • CCSprite继承自CCNode,所以你可以对它进行addChild的操作:
CCSprite *s1 = [CCSprite spriteWithFile:@"Icon.png"];  CCSprite *s2 = [CCSprite spriteWithFile:@"Icon.png"];  [s1 addChild:s2];  

四、精灵Z轴重设

[self reorderChild:sprite z:10];//selfCCLayer或者CCNode  

五、精灵换图

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

    (1)加载帧缓存

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

六、移除Sprite:

-(void)spriteMoveFinished:(id)sender {     CCSprite *sprite = (CCSprite *)sender;     [self removeChild:sprite cleanup:YES];}

七、精灵批处理(Sprite Batching):

  • 创建多个CCSprite节点,将它们添加到同一个CCSpriteBatchNode中以提高渲染速度
CCSpriteBatchNode* batch = [CCSpriteBatchNode batchNodeWithFile:@"bullet.png"];[self addChild:batch];for (int i = 0; i < 100; i++){    CCSprite* sprite = [CCSprite spriteWithFile:@"bullet.png"];    [batch addChild:bullet];}CCSprite* sprite = [CCSprite spriteWithFile:@"bullet.png"];[batch addChild:bullet];

什么时候应该使用CCSpriteBatchNode

当你需要显示两个或者更多个相同的CCSprite节点时,你可以使用CCSpriteBatchNode。组合在一起的CCSprite节点越多,使用 CCSpriteBatchNode得到的效果提升就越大

来源:http://group.cnblogs.com/topic/68312.html

0 0
原创粉丝点击