调用cc.RenderTexture 即可。
--需要截的屏幕大小
local render_texture = cc.RenderTexture:create(, )
--开始截屏
render_texture:begin()
--截self.node_container包含的内容
self.node_container:visit()
--关闭
render_texture:endToLua()
--调用
local photo_texture = render_texture:getSprite():getTexture()
local sprite_photo = cc.Sprite:createWithTexture(photo_texture)
--截屏后的sprite_photo为原始图片沿y轴翻转后的样子。若需要原图,调用如下函数.
sprite_photo:flipY()
local result = render_texture:saveToFile("share.png", cc.IMAGE_FORMAT_PNG)
-- saveToFile函数会默认添加根路径。
if not result then
print("save file failed")
end
注:若需要让某些图片强制渲染,调用sprite:visit()方法。
//C++对应的RenderTexture类的saveToFile方法。
bool RenderTexture::saveToFile(const std::string& fileName, Image::Format format, bool isRGBA)
{
CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG,
"the image can only be saved as JPG or PNG format");
if (isRGBA && format == Image::Format::JPG) CCLOG("RGBA is not supported for JPG format");
//保存图片文件的路径
std::string fullpath = FileUtils::getInstance()->getWritablePath() + fileName;
//初始化将纹理保存到文件的自定义渲染指令
_saveToFileCommand.init(_globalZOrder);
//设置自定义渲染指令的回调函数
_saveToFileCommand.func = CC_CALLBACK_0(RenderTexture::onSaveToFile, this, fullpath, isRGBA);
Director::getInstance()->getRenderer()->addCommand(&_saveToFileCommand);
return true;
}