Cocos2d-x   发布时间:2022-05-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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

大佬总结

以上是大佬教程为你收集整理的cocos2d-lua屏幕截屏的方法,超好用,亲测可行全部内容,希望文章能够帮你解决cocos2d-lua屏幕截屏的方法,超好用,亲测可行所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。