cocos2d-x Getting Screenshot with Blur

Utilize cocos2d-x ShaderTest under cpp-tests.

Using SpriteBlur class in the test, following code will add a screenshot with blur effect:

void GameLayer::screenshotBlur(float blurRadius, float blurSampleNum, int repeat)
{
    Size winSize= Director::getInstance()->getWinSize();
    // screenshot
    auto rt1= RenderTexture::create(winSize.width, winSize.height, Texture2D::PixelFormat::RGBA8888);
    rt1->begin();
    this->visit();
    rt1->end();
    
    RenderTexture* rt= rt1;

    for (int i= 0; i < repeat; i++)
    {
        // SpriteBlur
        auto sp1= SpriteBlur::create(rt->getSprite()->getTexture(), Rect(Vec2::ZERO, winSize));
        sp1->setAnchorPoint(Vec2::ZERO);
        sp1->setPosition(Vec2::ZERO);
        sp1->setFlippedY(true);
        sp1->setBlurRadius(blurRadius);
        sp1->setBlurSampleNum(blurSampleNum);
        
        // render blurred sprite
        rt= RenderTexture::create(winSize.width, winSize.height, Texture2D::PixelFormat::RGBA8888);
        rt->begin();
        sp1->visit();
        rt->end();
    }
    
    // final sprite
    auto sp2= Sprite::createWithTexture(rt->getSprite()->getTexture());
    sp2->setFlippedY(true);
    sp2->setPosition(winSize/2);
    sp2->setColor(Color3B(0x88, 0x88, 0x88));
    
    this->addChild(sp2);
}

The basic idea is as following:

  1. Using RenderTexture , get current scene’s screenshot
  2. With SpriteBlur , apply blur effect on the screenshot
  3. Render the SpriteBlur  to make a normal Texture
  4. Repeat
  5. Create a sprite with the texture of RenderTexture
  6. Add on the scene