如何在cocos2dx C ++ v3.10中更改Sprite纹理?

时间:2016-04-03 18:29:42

标签: c++ cocos2d-x cocos2d-x-3.0 cocos2d-x-3.x

我正在使用这个https://github.com/qiankanglai/ImagePicker ImagePicker实用程序我正在使用此代码来设置精灵纹理:

 void HelloWorldScene::didFinishPickingWithResult(cocos2d::Texture2D* result)
    {
        Size visibleSize = Director::getInstance()->getVisibleSize();
        Vec2 origin = Director::getInstance()->getVisibleOrigin();
        if(result == nullptr){
        return;
        }
       // sprite->removeFromParentAndCleanup(true);

        ClippingNode * clipper = ClippingNode::create();
        clipper->setPosition(visibleSize.width / 2, visibleSize.height / 2);
        clipper->setTag( kTagClipperNode );
        this->addChild(clipper);
        DrawNode * stencil = DrawNode::create();
        stencil->drawSolidCircle(Vec2(clipper->getBoundingBox().size.width / 2, clipper->getBoundingBox().size.height / 2), 100, 0, 200, Color4F::MAGENTA);
        clipper->setStencil(stencil);
        clipper->setInverted(false);
        auto sprite = cocos2d::Sprite::createWithTexture(result);
        sprite->setPosition( Vec2(clipper->getContentSize().width / 2, clipper->getContentSize().height / 2));
        clipper->addChild(sprite);
        this->addChild(clipper);
    }

实际上我从图库中获取纹理2D对象并将其设置在精灵上。 这段代码工作得很好但是如果我想替换sprite纹理,那么再次执行相同的代码并添加一个新的剪切节点对象,并且还会添加一个新的sprite ...

我想知道如何解决这个问题?当从图库中选择一张新照片时,我想用新的prite纹理替换旧的精灵纹理。

提前致谢!

1 个答案:

答案 0 :(得分:0)

Sprite在cocos2dx 3.0中有一个名为setTexture的成员函数。如果在场景中保留一个指向精灵对象的成员指针,则可以将函数更新为:

void HelloWorldScene::didFinishPickingWithResult(cocos2d::Texture2D* result)
    {
        if(result == nullptr){
           return;
        }
        if(m_sprite)
        {

           m_sprite->setTexture(result);
        }
        else 
        {
           Size visibleSize = Director::getInstance()->getVisibleSize();
           Vec2 origin = Director::getInstance()->getVisibleOrigin();
           ClippingNode * clipper = ClippingNode::create();
           clipper->setPosition(visibleSize.width / 2, visibleSize.height / 2);
           clipper->setTag( kTagClipperNode );
           this->addChild(clipper);
           DrawNode * stencil = DrawNode::create();
           stencil->drawSolidCircle(Vec2(clipper->getBoundingBox().size.width / 2, clipper->getBoundingBox().size.height / 2), 100, 0, 200, Color4F::MAGENTA);
           clipper->setStencil(stencil);
           clipper->setInverted(false);
           m_sprite = cocos2d::Sprite::createWithTexture(result);
           m_sprite->setPosition( Vec2(clipper->getContentSize().width / 2,clipper->getContentSize().height / 2));
           clipper->addChild(m_sprite);
           this->addChild(clipper);
        }
    }