cocos2dx 3.x(动态改变精灵的背景图片)

    //更换精灵CCSprite的图片有两种方式。

    

    //直接通过图片更换

    

    //使用setTexture(CCTexture2D*)函数,可以重新设置精灵类的纹理图片。

    

    //

    auto bg = Sprite::create();

    Texture2D* texture = Director::getInstance()->getTextureCache()->addImage("bg2.png");

    bg->setTexture(texture);

    //

    

    //2、通过缓存帧替换

    

    //使用setDisplayFrame(CCSpriteFrame*)函数,利用精灵帧更换精灵图片。

    

    

    //

    //加载plist文件到缓存

    SpriteFrameCache::getInstance()->addSpriteFramesWithFile("bg_0.plist");

    

    //使用精灵帧,创建精灵

    Sprite* bga = Sprite::createWithSpriteFrameName("bg1.png");

    

    //更换精灵图片

    SpriteFrame* frame = SpriteFrameCache::getInstance()->getSpriteFrameByName("bg2.png");

    bga->setSpriteFrame(frame);

    //

    

    /*//加载合成的图片

    CCSpriteBatchNode *spriteBatch=CCSpriteBatchNode::batchNodeWithFile("********.png");

    this->addChild(spriteBatch);

    //加载plist

    CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("myconfig.plist");

    // 生成Sprite

    CCSprite *headSprite=CCSprite::spriteWithSpriteFrameName("aaa.png");

    //需要更换图片时

    CCSpriteFrame *frame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("bbb.png");

    headSprite->setDisplayFrame(frame);

     

     */

 

 

 

 

  1. // 首先载入贴图集     
  2. CCSpriteBatchNode *spriteBatch=CCSpriteBatchNode::batchNodeWithFile("snake.png");    
  3. this->addChild(spriteBatch);    
  4. CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("snake.plist");    
  5. // 生成Sprite     
  6. CCSprite *headSprite=CCSprite::spriteWithSpriteFrameName("headup.png");    
  7. //需要更换图片时     
  8. CCSpriteFrame *frame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("headleft.png");    
  9. headSprite->setDisplayFrame(frame);

 

 

 

 

  1. CCSprite *my_hero = CCSprite::create("hero_a.png");  
  2.   
  3. CCTexture2D *hero_hit;  
  4.   
  5. CCSprite * temp_obj = CCSprite::create("hero_hit.png");  
  6.   
  7.  hero_hit = temp_obj->getTexture();  
  8.   
  9.   
  10. //改变my_hero的图片  
  11.  my_hero->stopAllActions();  
  12.   
  13. my_hero->setTexture(hero_hit);  

 

原文地址:https://www.cnblogs.com/luorende/p/6028853.html