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

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

概述cocos2d-x lua系统自带截屏功能,使用方便。代码如下: local fileName = "printScreen.png" -- 移除纹理缓存 cc.Director:getInstance():getTextureCache():removeTextureForKey(fileName) self:removeChildByTag(10

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)endfunction 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 = nilfunction WeixinShareTips : ctor()    self.root = cc.csloader:createNode(WeixinShareTips.RESOURCE_filename)    self:addChild(self.root)    self:enableNodeEvents()    this = selfendfunction WeixinShareTips : getResourceNode()    return self.rootendfunction 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)endfunction WeixinShareTips.startShareWithNodeAndshareCurrentSece(dstNode,isShareCurrentScene)    local WeixinTips = WeixinShareTips : create()    dstNode : addChild(WeixinTips)    WeixinShareTips.isShareCurrentScene = isShareCurrentSceneendfunction 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--重置UIfunction 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 nodeendfunction WeixinShareTips : onExit()    self : removeAllChildren()endfunction 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    endend--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) endfunction WeixinShareTips.createWeixinImagefile(bShareCurrentScene,backGroundNode)    return createImagefileWithRenderTexture(renderTexture)endreturn WeixinShareTips
总结

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

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1077547.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存