cocos2d-lua屏幕截屏的方法,超好用,亲测可行

前端之家收集整理的这篇文章主要介绍了cocos2d-lua屏幕截屏的方法,超好用,亲测可行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

cocos2d-x lua系统自带截屏功能,使用方便。代码如下:

local fileName = "printScreen.png"
        -- 移除纹理缓存
        cc.Director:getInstance():getTextureCache():removeTextureForKey(fileName)
        self:removeChildByTag(1000)
        -- 截屏
        cc.utils:captureScreen(function(succeed,outputFile)
            if succeed then
              local winSize = cc.Director:getInstance():getWinSize()
              local sp = cc.Sprite:create(outputFile)
              self:addChild(sp,1000)
              sp:setPosition(winSize.width / 2,winSize.height / 2)
              sp:setScale(0.5) -- 显示缩放
                print(outputFile)
            else
                cc.showTextTips("截屏失败")
            end
        end,fileName)


第二种方法,一帧之内进行截图并把纹理保存到本地的方法

关键代码

function WeixinShareTips.createWeixinImageFile(bShareCurrentScene,func_next)

    local imgSize = cc.size(640,960)
    local backGround = {
        path = "weixin/background_twoDimension.jpg",pos = cc.p(imgSize.width / 2,imgSize.height / 2),scale = 1
    }
    local logo = {
        path = cc.logos[cc.getSDKPlat()],pos = cc.p(503,848),scale = 0.51
    }
    local twoDimension = {
        path = nil,pos = cc.p(532,106),scale = 1
    }

    if bShareCurrentScene then
        backGround = nil
        logo.pos = cc.p(117,550)
        twoDimension = nil
        imgSize = cc.size(960,640)
        logo.scale = 0.3
    elseif cc.getSDKPlat() == "ios_yd" then
        twoDimension.path = "weixin/twoDimension_bierangwomaoxian.jpg"
    elseif cc.getSDKPlat() == "ios_yd2" then
        twoDimension.path = "weixin/twoDimension_maoxianqishituan.jpg"
    elseif cc.getSDKPlat() == "ios_yd3" then
        twoDimension.path = "weixin/twoDimension_menghuanqishituan.jpg"
    else
        backGround.path = "weixin/background_noDimension.jpg"
        twoDimension = nil
    end

    local bigImagePath = WeixinShareTips.createWeixinImageFileWithlogoAndTwoDimension("bigWeixinShare.jpg",backGround,logo,twoDimension,imgSize)
    local saveRet = bigImagePath ~= nil

    local function delayDoSomething(call_todo)
        cc.Director : getInstance() : getRunningScene()  : runAction(cc.Sequence:create(
        cc.DelayTime:create(0.1),cc.CallFunc:create(function ()
            call_todo()
        end)))
    end

    delayDoSomething(function()
        local imgScale = 1/8
        imgSize = cc.size(imgSize.width * imgScale,imgSize.height * imgScale)
        backGround = {
            path = bigImagePath,scale = imgScale
        }

        local smallImagePath = WeixinShareTips.createWeixinImageFileWithlogoAndTwoDimension("smallWeixinShare.jpg",nil,imgSize)
        delayDoSomething(function()
            saveRet = saveRet and (smallImagePath ~= nil)
            func_next(saveRet,smallImagePath,bigImagePath)
        end)
    end)
end

function WeixinShareTips.createWeixinImageFileWithlogoAndTwoDimension(toFileName,imgSize)

    local function createRenderNodeWithPathPos(pathPos)
        local sprite = nil
        if pathPos then
            sprite = cc.Sprite:create(pathPos.path)
            sprite : setPosition(pathPos.pos)
            sprite : setScale(pathPos.scale)
        end
        return sprite
    end

    local function createRenderTextureWithNodes(logoRenderNode,twoDimensionNode,backGroundNode)
          -- body
        local renderTexture = cc.RenderTexture:create(imgSize.width,imgSize.height)

        renderTexture : beginWithClear(0,0)

        if backGroundNode and (cc.Director:getInstance():getRunningScene() ~= backGroundNode) then
            backGroundNode : getTexture() : setTexParameters(cc.GL_LINEAR,cc.GL_LINEAR,cc.GL_CLAMP_TO_EDGE,cc.GL_CLAMP_TO_EDGE)
        end

        if backGroundNode then
            backGroundNode : visit()
        end
       

        if logoRenderNode then
            logoRenderNode : visit()
        end

        if twoDimensionNode then
            twoDimensionNode : visit()
        end

        renderTexture : endToLua()
        return renderTexture
    end

    local function createImageFileWithRenderTexture(renderTexture)
        local saveRet = renderTexture : saveToFile(toFileName,cc.IMAGE_FORMAT_JPEG,false)
        cc.Director : getInstance() : getTextureCache() : removeTextureForKey(
            cc.FileUtils:getInstance():getWritablePath() .. toFileName)
        if saveRet then
           return cc.FileUtils:getInstance():getWritablePath() .. toFileName
        else
            cc.showTextTips("保存图片失败")
            return nil
        end
    end

    local logoNode =  createRenderNodeWithPathPos(logo)
    local twoDimensionNode = createRenderNodeWithPathPos(twoDimension)
    local backGroundNode = createRenderNodeWithPathPos(backGround)
    if not backGroundNode then
        backGroundNode = cc.Director:getInstance():getRunningScene()
    end
    
    local renderTexture = createRenderTextureWithNodes(logoNode,backGroundNode)
    return createImageFileWithRenderTexture(renderTexture)
end

用法代码如下:(WeixinShareTips.lua)
local WeixinShareTips = class("WeixinShareTips",cc.Node)
local EventTips = import(".EventTips")
local NoticeLayer = import(".NoticeLayer")
local EvaluateLayer = import(".EvaluateLayer")
local GuideLayer = import(".GuideLayer")

WeixinShareTips.RESOURCE_FILENAME = "WeixinShareTips.csb"

--一些变量
local lsl = LuaSerialize:getInstance()
local this = nil

function WeixinShareTips : ctor()
    self.root = cc.CSLoader:createNode(WeixinShareTips.RESOURCE_FILENAME)
    self:addChild(self.root)
    self:enableNodeEvents()
    this = self
end

function WeixinShareTips : getResourceNode()
    return self.root
end

function WeixinShareTips.getShareRewardFromServer()
    print("SHARE_SUCCESS")
      --请求数据
    lsl:clear()
    lsl:writeShort(111)
    lsl:writeBytes(cc.userSid,8)
    local data = lsl:getBytes()
    cc.sendReq(cc.gameServer,data,function (msg,sc,rc)
            if sc == 0 and rc == 0 then
                cc.showTextTips("分享成功,请在邮件中查收奖品")
            elseif rc == 109 then
                print("今日已领取奖励")
            else
                cc.showTextTips("sc:" .. sc .. " rc:" .. rc)
            end
        end)
end

function WeixinShareTips.startShareWithNodeAndshareCurrentSece(dstNode,isShareCurrentScene)
    local WeixinTips = WeixinShareTips : create()
    dstNode : addChild(WeixinTips)
    WeixinShareTips.isShareCurrentScene = isShareCurrentScene
end

function WeixinShareTips : onEnter()
    --按钮事件
      --mask
    self : getResourceNode() : getChildByName("pnl_mask") : addClickEventListener(
    function ()
        cc.gameSound:playClickSound()
        self : removeFromParent()
    end)


    self : getResourceNode() : getChildByName("btn_shareAll") : addClickEventListener(
    function ()
        cc.gameSound:playClickSound()
        self : removeFromParent()
        
        WeixinShareTips.createWeixinImageFile(WeixinShareTips.isShareCurrentScene,function(success,bigImagePath)
            if success then
                WeixinShareTips.sendWeixinImage(cc.const.TOALLFRIENDS,bigImagePath)
            end
        end)
    end)

    self : getResourceNode() : getChildByName("btn_shareFriend") : addClickEventListener(
    function ()
        cc.gameSound:playClickSound()
        self : removeFromParent()
        WeixinShareTips.createWeixinImageFile(WeixinShareTips.isShareCurrentScene,bigImagePath)
            if success then
                WeixinShareTips.sendWeixinImage(cc.const.TOFRIEND,bigImagePath)
            end
        end)
    end)

    self : initUI()
end


--重置UI
function WeixinShareTips : initUI()
    local pnl_smallItem = self.root : getChildByName("pnl_smallItem")
    local pnl_hero = self.root : getChildByName("pnl_hero")
    local itemInterval = 82
    local heroInterval = 110

    local rewards = cc.parseCombainCfg(cc.csvData["global"]["wxShareRewardShow"])
    local node = self : createRewardNode(pnl_smallItem,pnl_hero,itemInterval,heroInterval,rewards)
    self.root : getChildByName("pnl_posTop") : addChild(node)

    rewards = cc.parseCombainCfg(cc.csvData["global"]["wxShareFirstRewardShow"])
    node = self : createRewardNode(pnl_smallItem,rewards)
    self.root : getChildByName("pnl_posDown") : addChild(node)
end

--创建奖励,pnl_smallItem: 小项的panle,pnl_hero:英雄背景,itemInterval:列间距,heroInterval英雄间距,rewards:奖励
function WeixinShareTips : createRewardNode(pnl_smallItem,rewards)

    --创建角色等待动画
   local function createARoleWithShadow(name,qlty,scale)
        local node = ccui.Widget : create()
        local anim = cc.createRoleAnim(name,qlty == "6")
        anim:setName("anim")
        anim:getAnimation():play("wait",-1,1)
        anim:setScale(scale)
        node:addChild(anim)
        anim:setPosition(45,13)
        node : setContentSize(cc.size(100,100))
        return node
    end

    local function func_showHero(sender)
          -- body
        local heroCode = tostring(sender : getTag())
        local hero = cc.csvData["heros"][heroCode]
        EventTips.getInstance():showTips(this)
        hero.new = false

        hero.hit = 0       --命中
        hero.crit = 0      --暴击
        hero.def = 0       --防御
        hero.dodge = 0     --闪避 
        hero.ethos = 0     --王者
        hero.speed = 0    --速度

        EventTips.getInstance():showHero(hero,true)
    end

    local function setHeroPanelInfoWithCode(panel,heroCode)
        local qlty = cc.csvData["heros"][heroCode]["qlty"]
        local anim = createARoleWithShadow(cc.csvData["heros"][heroCode]["appearance"],0.35)
        anim : setPosition(cc.p(47,45))

        panel : setVisible(true)
        panel : getChildByName("img_anim") : removeChildByTag(1024)
        panel : getChildByName("img_anim") : addChild(anim)
        anim : setTag(1024)
        panel : getChildByName("img_anim") : setTag(heroCode)
        panel : getChildByName("img_anim") : loadTexture("icon/ui_ctn_layer_Box0" .. qlty ..".png")
        panel : getChildByName("img_anim") : addClickEventListener(func_showHero)
    end

    local function func_showItemTips(sender,touchType)
        local code = tostring(sender : getTag())

        if touchType == cc.const.TOUCH_EVENT_BEGAN then
            local img_BoxSize = sender : getContentSize()
            --began
            cc.gameSureTips:showItemTips(
                sender,code,cc.p(img_BoxSize.width / 2,img_BoxSize.height + 6)
            )
        elseif touchType == 1 then
            --moved
        else
            --ended or canceled
            local tips = sender : getChildByName("showItemTips")
            if tips then
                tips.close()
            end
        end
    end

    local function setItemInfoWithReward(pnl_item,reward,img_BoxName)
        local img_Box = pnl_item : getChildByName("img_Box")
        img_Box : setName(img_BoxName)
        img_Box : loadTexture(cc.getResIconName(reward.aType)) --icon
        img_Box : setTouchEnabled(true)

        --数值类型
        if reward.code == "0" then
            reward.code = tostring(900000 + tonumber(reward.aType))
        end

        img_Box:loadTexture("icon/ui_icon_Box"..cc.csvData["items"][reward.code]["qlty"]..".png")
        img_Box:getChildByName("img_icon")
            :loadTexture("icon/"..cc.csvData["items"][reward.code]["icon"]..".png")
        img_Box:getChildByName("txt_count"):setString(reward.count)

        img_Box : addTouchEventListener(func_showItemTips)
        img_Box : setTag(reward.code)
        img_Box : setSwallowTouches(false)
    end

    local startPos = cc.p(0,0) --起点位置
    local node = ccui.Widget : create()

    for i = 1,#rewards,1 do
        local isHero = (rewards[i][1] == "100") --是否为英雄

        if isHero then
            --创建角色
            local pnl_isHero = pnl_hero : clone()
            node : addChild(pnl_isHero)
            pnl_isHero : setPosition(startPos)
            local heroCode = rewards[i][2]
            setHeroPanelInfoWithCode(pnl_isHero,heroCode)
            startPos.x = startPos.x + heroInterval
        else
            local pnl_item = pnl_smallItem : clone()
            pnl_item : setVisible(true)
            node : addChild(pnl_item)

            local reward = {
                aType = rewards[i][1],code = rewards[i][2],count = rewards[i][3]
            }
            setItemInfoWithReward(pnl_item,"img_Box_" .. i)
            pnl_item : setPosition(startPos)
            startPos.x = startPos.x + itemInterval
        end

    end

    return node
end


function WeixinShareTips : onExit()
    self : removeAllChildren()
end

function WeixinShareTips.addShareButtonTo(dstNode)

    local function func_btnShare()
       WeixinShareTips.startShareWithNodeAndshareCurrentSece(dstNode,true)
    end

    local shareOpen = not(cc.weixinID == nil or  cc.weixOpen == nil or cc.weixOpen == "0")
    if not shareOpen then
        return nil
    else
        dstNode : removeChildByName("weixinShareButton")

        local btn = ccui.Button : create()
        dstNode : addChild(btn)

        btn : setName("weixinShareButton")
        btn : loadTextures("weixin/ui_btn_share_normal.png","weixin/ui_btn_share_selected.png","")
        btn : setLocalZOrder(12345)
        btn : setPosition(cc.p(898,54))

        btn : setTouchEnabled(true)
        btn : addClickEventListener(func_btnShare)

        return btn
    end
end


--mode:0发给朋友,1发到朋友圈,smallPng:小图片,bigPng:大图
function WeixinShareTips.sendWeixinImage(mode,smallPng,bigPng)
    -- body
    -- local mode = "1"
    -- local smallPng = "test.png"
    -- local bigPng = "testBig.png"
    local info = "8;" .. mode .. ";" ..smallPng .. ";" ..bigPng .. ";" .. cc.weixinID 
    cc.dataEye(info) 
end

--mode:0发给朋友,Png:图片
function WeixinShareTips.sendWeixinURL(mode,png,title,desc,url)
    -- body
    --  local mode = "1"
    -- local png = "test.png"
    -- local title = "TITLE-------TITLE"
    -- local desc = "DESC--------DESC"
    -- local url = "http://www.baidu.com"
    -- local mode = "1"
    local info = "9;" .. png .. ";" ..title .. ";" ..desc .. ";" .. url .. ";" .. mode .. ";" ..cc.weixinID
    cc.dataEye(info) 
end

function WeixinShareTips.createWeixinImageFile(bShareCurrentScene,backGroundNode)
    return createImageFileWithRenderTexture(renderTexture)
end

return WeixinShareTips
原文链接:https://www.f2er.com/cocos2dx/340212.html

猜你在找的Cocos2d-x相关文章