Render To Texture
Overview
Textures are used to be loaded from file or other IO streams. Besides this, we provide a new mechanism RenderTexture
to generate a texture runtime. Then you can get the grabbed texture, create sprite, create texture atlas etc.
Work flow
The workflow of using RenderTexture:
Grab rendered contents
1 2 3 4 | auto renderTexture = RenderTexture::create(width, height, format);
renderTexture->begin();
sprite->visit();
renderTexture->end();
|
1 2 3 4 | local renderTexture = RenderTexture:create(width, height, format) renderTexture:begin() sprite:visit() renderTexture:end() |
Using rendered texture
Given that you have a rendered texture, you can using the RenderTexture to do things you want.
Using it to create a sprite
Texture2D
can be got from the RenderedTexture, then based on this texture, we can create a sprite and add it to the scene. It could be created even if we have not grabbed the rendered contents.
1 2 3 | auto sprite = Sprite::create();
sprite->initWithTexture(_target->getSprite()->getTexture());
scene->addChild(sprite);
|
1 2 3 | local sprite = Sprite:create() sprite:initWithTexture(renderTexture:getSprite():getTexture()) scene:addChild(sprite) |
Saving RenderTexture to file
Saving RenderTexture contents to scene can only be called after we grabbed the rendered contents. What we need to do is the specify the file path and an optional file format.
1 | renderTexture->saveToFile(filePath); |
1 | renderTexture:saveToFile(filePath) |
One more thing is that saving RenderTexture contents to a file is asynchronized, we just add a RenderCommand
to the renderer which will be call later in this frame. So you can not get the file result immediately after the function call. The actual file saving will be happened when Renderer
executes the RenderCommand
.