cocos版本:2.4.4
參考:
游戲中可能會用到截圖功能,利用攝像機組件camera進行截圖。
一 截圖指定node
如下圖,對heroNode進行截圖。

MainScene.ts代碼如下:
const { ccclass, property } = cc._decorator;
@ccclass
export default class MainScene extends cc.Component {
@property(cc.Node) //截圖目標節點
heroNode: cc.Node = null;
start() {
let node = this.screenShot(this.heroNode);
node.x = 0;
node.y = 0;
node.parent = this.node;
}
/**
* 截圖
* @param targetNode 截圖目標節點,如果為null則表示截全屏
* @returns 返回截屏圖片的node
*/
screenShot(targetNode: cc.Node = null) {
//獲取當前場景Camera
let camera = cc.director.getScene().getComponentInChildren(cc.Camera);
//創建新的texture
let texture = new cc.RenderTexture();
texture.initWithSize(cc.winSize.width, cc.winSize.height, (cc.game as any)._renderContext.STENCIL_INDEX8);
//創建新的spriteFrame
let spriteFrame = new cc.SpriteFrame();
if (targetNode == null) {
spriteFrame.setTexture(texture);
} else {
let nodeX = cc.winSize.width / 2 + targetNode.x - targetNode.width / 2;
let nodeY = cc.winSize.height / 2 + targetNode.y - targetNode.height / 2;
let nodeWidth = targetNode.width;
let nodeHeight = targetNode.height;
//只顯示node部分的圖片
spriteFrame.setTexture(texture, new cc.Rect(nodeX, nodeY, nodeWidth, nodeHeight));
}
//創建新的node
let node = new cc.Node();
let sprite = node.addComponent(cc.Sprite);
sprite.spriteFrame = spriteFrame;
//截圖是反的,這里將截圖scaleY取反,這樣就是正的了
sprite.node.scaleY = - Math.abs(sprite.node.scaleY);
//手動渲染camera
camera.cullingMask = 0xffffffff;
camera.targetTexture = texture;
camera.render();
camera.targetTexture = null;
return node;
}
}
截圖效果,可見人物只截取了node范圍內的部分。

二 截圖全屏
直接調用上面代碼的screenShot(),不傳入參數,就是截圖全屏。
start() {
let node = this.screenShot();
node.x = 0;
node.y = 0;
node.parent = this.node;
}
截圖了全屏

