RenderTexturer 如何获取(修改)像素点信息

RenderTexturer 如何获取(修改)像素点信息

  • Creator 版本: 3.3.1

  • 目标平台: 任何平台

  • 之前哪个版本是正常的: 2.4.5

  1. 之前 2.0 有提供readPixels方法, 3.0 版本没有这个方法, 查看了源代码, 也没有很好的解决方式. 官方是否提供一个获取像素点信息的方法或者思路?

  2. 需要对图片上的像素进行修改, 之前用RenderTexture.initWithData, 现在 3.0 版本的RenderTexture没有这个方法.

1赞

你好,
问题1: 之前3.0版本,确实没有readPixels方法。不过在3.4.0版本重新开放这个接口。
https://github.com/cocos-creator/engine/pull/9396/files

问题2: RenderTexture.initWithData这个确实没有了。你可以考虑使用 imageAsset -> Texture2D -> SpriteFrame 的方式。 可以参考 技术支持游戏技术分享方案-画板

感谢回复~

我的需求是获取贴图的像素并修改像素,但是没有initWithData就没法用已有的贴图初始化RenderTexture了,那就算是有readRixels也没有用呀,因为没有数据读出来的renderTexture的值肯定是一堆的0,请问下,有没有在3.4版本用图片初始化renderTexture的方案呢

已经解决了,给texture2D重写一个readRixels方法即可 :nerd_face:

1赞

你好,我想问一下,具体要怎么实现呢

重写代码就是抄引擎里面的代码,放在你自己的公用库或者你认为合适的地方,实现如下:

public readPixels (texture:Texture2D, x = 0, y = 0, width?: number, height?: number) : Uint8Array | null {
    width = width || texture.width;
    height = width || texture.height;
    const gfxTexture = texture.getGFXTexture();
    if (!gfxTexture) {
        return null;
    }
    const bufferViews: ArrayBufferView[] = [];
    const regions: gfx.BufferTextureCopy[] = [];

    const region0 = new gfx.BufferTextureCopy();
    region0.texOffset.x = x;
    region0.texOffset.y = y;
    region0.texExtent.width = width;
    region0.texExtent.height = height;
    regions.push(region0);

    const buffer = new Uint8Array(width * height * 4);
    bufferViews.push(buffer);

    director.root?.device.copyTextureToBuffers(gfxTexture, bufferViews, regions)

    return buffer;
}

// 使用的方法mainTexture就是你想要修改的贴图,readPixels出来的就是贴图的详细信息,想怎么改就怎么改了
// 获取旧贴图的内存数据 是一个线性数组 一个矩阵
let imgData = this.readPixels(mainTexture);

4赞

该主题在最后一个回复创建后14天后自动关闭。不再允许新的回复。