- Published on
3.x获取像素颜色
- Authors

- Name
- Muzzik(马赛克)
通过世界坐标获取屏幕像素颜色
效果图

实现步骤
新建一个 RenderTexture
复制场景内 canvas 下的摄像机节点 \

在复制的节点 camera 设置 target texture 为之前创建的 RenderTexture \

取色代码
// 取色之前一定要重置 RenderTexture 的大小和当前 Canvas 大小一致,只需要执行一次(屏幕大小变更时也需执行)
camera_rt.targetTexture!.resize(
cc.view.getDesignResolutionSize().width,
cc.view.getDesignResolutionSize().height
)
const pos_v2 = 世界坐标
const color_as = camera_rt.targetTexture!.readPixels(pos_v2.x, pos_v2.y, 1, 1)!
// 获得颜色
cc.color(color_as[0], color_as[1], color_as[2], color_as[3])
示例代码:
const camera_rt = this.nodes.cameraRT.getComponent(cc.CameraComponent)!
camera_rt.targetTexture!.resize(
cc.view.getDesignResolutionSize().width,
cc.view.getDesignResolutionSize().height
)
this.node.on(
cc.Node.EventType.TOUCH_MOVE,
(event: cc.EventTouch) => {
const pos_v2 = event.getUILocation()
const color_as = camera_rt.targetTexture!.readPixels(pos_v2.x, pos_v2.y, 1, 1)!
this.nodes.color.sprite.color = cc.color(color_as[0], color_as[1], color_as[2], color_as[3])
},
this
)
