微信小游戏Cocos Creator小游戏

cocos creator2.0截图分享

2019-05-15  本文已影响4人  897dc7b51c3c

ccc2.0后修改了jsb的截图方式,导致原1.x的截图方式不可用。
这里分享一下新的截图代码,以供参考:

//截图,传入被截图的node及回调函数
    captureScreen(node, fn) {
        let width = Math.floor(node.width);
        let height = Math.floor(node.height);
        if (CC_JSB) {
            let fileName = "result_share.jpg";
            let fullPath = jsb.fileUtils.getWritablePath() + fileName;
            if (jsb.fileUtils.isFileExist(fullPath)) {
                jsb.fileUtils.removeFile(fullPath);
            }
            let cameraNode = new cc.Node();
            cameraNode.parent = node.parent;
            let camera = cameraNode.addComponent(cc.Camera);
            camera.cullingMask = 0xffffffff;
            let texture = new cc.RenderTexture();
            let gl = cc.game._renderContext;
            texture.initWithSize(width, height, gl.STENCIL_INDEX8);
            camera.targetTexture = texture;
            camera.render(node);
            let data = texture.readPixels();
            //以下代码将截图后默认倒置的图片回正
            let picData = new Uint8Array(width * height * 4);
            let rowBytes = width * 4;
            for (let row = 0; row < height; row++) {
                let srow = height - 1 - row;
                let start = Math.floor(srow * width * 4);
                let reStart = row * width * 4;
                // save the piexls data
                for (let i = 0; i < rowBytes; i++) {
                    picData[reStart + i] = data[start + i];
                }
            }
            //保存图片
            jsb.saveImageData(picData, width, height, fullPath);
            console.log("截图成功,图片保存在 ====>", fullPath);
            node.parent.removeChild(camera);
            if (fn) fn(fullPath);
        } 
    },
上一篇 下一篇

猜你喜欢

热点阅读