Change png used by sprite

In cocos2d-x, how can I change the png used by the sprite?

The following steps, however, seem a bit long, and I was wondering if there is an alternative that prevents me from calling new ?

 // create sprite with original png m_pSpr = CCSprite::create( "1.png" ); m_pSpr->setPosition( ccp( 100, 100 ) ); this->addChild( m_pSpr ); // now change the png that is used by the sprite // new image from png file CCImage* img = new CCImage(); img->initWithImageFile( "2.png", CCImage::kFmtPng ); // new texture from image CCTexture2D* tex = new CCTexture2D(); tex->initWithImage( img ); // finally change texture of sprite m_pSpr->setTexture( tex ); 
+4
source share
3 answers

Pack the sprites in the spritesheet, then use CCSprite setDisplayFrame ().

 // make sure the spritesheet is cached auto cacher = CCSpriteFrameCache::sharedSpriteFrameCache(); cacher->addSpriteFramesWithFile("Spritesheet.plist"); // create the sprite m_pSpr = CCSprite::create( "1.png" ); // set it display frame to 2.png CCSpriteFrame* frame = cacher->spriteFrameByName("2.png"); if( frame) m_pSpr->setDisplayFrame(frame); 
+5
source

You cannot use the setTexture method for a single sprite. If you pack sprites in atlases (one texture, for example, 2048x2048 pixels with many different frames inside it, which allows to reduce the amount of memory), this method sets the whole huge texture to your sprite. Use setDisplayFrame instead

+2
source

you can, but what Morion said is correct, try to avoid using the code below because it is expensive. try using TexturePacker and dealing with Sprite frames is a good idea.

 yourSprite->setTexture(CCTextureCache::sharedTextureCache()->addImage("2.png")); 
+1
source

Source: https://habr.com/ru/post/1439599/


All Articles