天天看點

quick cocos 截屏并儲存

調用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;  
}