【工具類】CocosCreator 截屏(全屏,指定node區域)


cocos版本:2.4.4

參考:

cocos官方文檔-攝像機截圖

 

游戲中可能會用到截圖功能,利用攝像機組件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;
    }

 

截圖了全屏  

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM