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轴倒转的