cocos creator 2.+ 原生(Android/IOS)截屏

capture(){
        let node = new cc.Node();
        node.parent = cc.director.getScene();
        node.width = cc.view.getVisibleSize().width;
        node.height = cc.view.getVisibleSize().height;
        
        //注意了,这里要讲节点的位置改为右上角,不然截图只有1/4
        node.x = node.width/2;
        node.y = node.height/2;

        let camera = node.addComponent(cc.Camera);
        // 设置你想要的截图内容的 cullingMask
        camera.cullingMask = 0xffffffff;
        
        // 新建一个 RenderTexture,并且设置 camera 的 targetTexture 为新建的 RenderTexture,这样 camera 的内容将会渲染到新建的 RenderTexture 中。
        let texture = new cc.RenderTexture();
        texture.initWithSize(node.width, node.height);
        camera.targetTexture = texture;

        // 渲染一次摄像机,即更新一次内容到 RenderTexture 中
        node.parent.scaleY = -1;  // 截图默认是y轴反转的,渲染前需要将图像倒过来,渲染完倒回去
        camera.render();
        node.parent.scaleY = 1

        // 这样我们就能从 RenderTexture 中获取到数据了
        let data = texture.readPixels();
        let width = texture.width;
        let height = texture.height;

        this.captureAction(node, width, height); //做个截屏的动作

        let fileName = "result_share.jpg";
        let fullPath = jsb.fileUtils.getWritablePath() + fileName;
        if (jsb.fileUtils.isFileExist(fullPath)) {
            jsb.fileUtils.removeFile(fullPath);
        }
        let success = jsb.saveImageData(data, width, height, fullPath);
        var self = this; //保存this对象,否则加载图片回调方法会找不到
        if (success) {
            cc.log("截屏成功,fullPath,width,height = ",fullPath,width,height);
            cc.loader.load(fullPath, function(err, tex){  //读取本地文件,刷新需要显示的sprite控件
                if( err ){
                    cc.error(err);
                }else{
                    var spriteFrame = new cc.SpriteFrame(tex);
                    if( spriteFrame ){
                        self.logo.getComponent(cc.Sprite).spriteFrame = spriteFrame;
                        console.log("刷新logo")
                    }
                }
            });
        }
        else {
            cc.error("截屏失败!");
        }
    },

    //截屏动画
    captureAction (capture, width, height) {
        let scaleAction = cc.scaleTo(1,0.3);
        let targetPos = cc.v2(width - width / 6,  height / 4);
        let moveAction = cc.moveTo(1, targetPos); 
        let spawn = cc.spawn(scaleAction, moveAction);
        capture.runAction(spawn);
        let blinkAction = cc.blink(0.1, 1);
        this.node.runAction(blinkAction);
    },

官方demo给的例子跑起来还是有报错,这里放个自己实现的方法,注意的地方有两个:

(1)截图node的位置需要放置在屏幕的右上角,否则截图只有1/4,屏幕

(2)渲染摄像机前需要将场景y轴翻转,否则截取屏幕会是y轴倒转的

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值