@ccclass
@executionOrder(-1)
export default class RenderingGroup extends cc.Component {
//输入的相机,不能为主相机,要新建一个
@property(cc.Camera)
protected inputCamera: cc.Camera = null;
//输出的图像
@property(cc.Sprite)
protected outputSprite: cc.Sprite = null;
//输出纹理
protected renderTexture: cc.RenderTexture = null;
/**
* 生命周期:加载
*/
protected onLoad() {
this.init();
this.registerEvent();
}
/**
* 生命周期:销毁
*/
protected onDestroy() {
this.unregisterEvent();
this.release();
}
/**
* 注册事件
*/
protected registerEvent() {
cc.Canvas.instance.node.on(cc.Node.EventType.SIZE_CHANGED, this.onCanvasSizeChanged, this);
}
/**
* 关闭注册事件
*/
protected unregisterEvent() {
cc.Canvas.instance.node.off(cc.Node.EventType.SIZE_CHANGED, this.onCanvasSizeChanged, this);
}
/**
* 初始化
*/
protected init() {
this.getCameraTexture(this.node)
// 新建一个 RenderTexture,并且设置 camera 的 targetTexture 为新建的 RenderTexture,
// 这样 camera 的内容将会渲染到新建的 RenderTexture 中。
const renderTexture = this.renderTexture = new cc.RenderTexture(),
screenSize = cc.view.getVisibleSizeInPixel();
renderTexture.initWithSize(screenSize.width, screenSize.height);
// 将摄像机的内容渲染到目标纹理上
this.inputCamera.targetTexture = renderTexture;
// 使用目标纹理生成精灵帧并设置到精灵上
this.outputSprite.spriteFrame = new cc.SpriteFrame(renderTexture);
this.outputSprite.node.scaleY = -Math.abs(this.outputSprite.node.scaleY);
}
/**
* 释放
*/
protected release() {
this.renderTexture.destroy();
}
/**
* 画布尺寸变化回调
*/
protected onCanvasSizeChanged() {
const screenSize = cc.view.getVisibleSizeInPixel();
this.renderTexture.initWithSize(screenSize.width, screenSize.height);
}
/**
* 获取节点整体图像
* @param node
* @returns
*/
public getCameraTexture(node: cc.Node): cc.Camera {
if (this.inputCamera) return this.inputCamera
let camera = node.addComponent(cc.Camera);
// 设置你想要的截图内容的 cullingMask
camera.cullingMask = 0;
camera.cullingMask |= (1 << 3);//group所在的分组
// // 当相机everything 时,cullingMask 为 -1,即32个1,0xffffffff;
// // 当相机nothing 时,cullingMask 等于 0;
// // 渲染除去层x的所有层
// camera.cullingMask = ~(1 << x);
// // 关闭(减掉)层 x
// camera.cullingMask &= ~(1 << x);
// // 打开(增加)层 x
// camera.cullingMask |= (1 << x);
// // 摄像机只显示第x层, y层, z层.
// camera.cullingMask = (1 << x) + (1 << y) + (1 << z);
camera.clearFlags = cc.Camera.ClearFlags.STENCIL | cc.Camera.ClearFlags.DEPTH;
camera.depth = 0;
camera.rect = cc.rect(0, 0, 1, 1);
camera.zoomRatio = Math.min(cc.winSize.height / node.height, cc.winSize.width / node.width)
this.inputCamera = camera
return camera;
}
}
【cocos creator】【sharder】渲染相机图像到指定图片上,可对图片进行shardr操作
于 2024-08-27 15:57:21 首次发布