cocos将节点保存为图片,在保存至相册

---把某个节点渲染并保存为图片
---@param node Node 需要保存的节点
---@param imageName string|nil 图片名字
---@param callback function|nil 成功回调
---@return void
function TestSaveImage(node, imageName, callback )
    if tolua.isnull(node) then
        return
    end
    local dirPath = cc.FileUtils:getInstance():getWritablePath() .. "imgName"
    imageName = imgName or "image-" .. os.date("%Y%m%d%H%M");
    local path = string.format("%s/%s.png", dirPath, imageName)
    if cc.FileUtils:getInstance():isFileExist(path) then
        if callback then
            callback(path)
        else
            callback(false)
        end
        return
    end
    local size = node:getContentSize()
    local renderTexture = cc.RenderTexture:create(size.width, size.height,cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888)
    local ap = node:getAnchorPoint()
    local p = cc.p(node:getPosition())
    node:setVisible(true)
    --设置位置到左下角
    node:setPosition(cc.p(ap.x * size.width  ,ap.y * size.height))
    renderTexture:begin()
    node:visit()
    renderTexture:endToLua()

    renderTexture:retain()
    performWithDelay(node,function()
        if not cc.FileUtils:getInstance():isDirectoryExist(dirPath) then
            cc.FileUtils:getInstance():createDirectory(dirPath)
        end
        node:setPosition(p)
        renderTexture:newImage():saveToFile(savePath, false)
        renderTexture:release()
        if callback then
            callback(savePath)
        end
    end,0.01)
end

 

posted @ 2019-04-26 16:58  履霜坚冰  阅读(1665)  评论(0编辑  收藏  举报