creator3.x获取图片像素
/**
* 获取贴图中的像素
* @param tex 贴图资源,可以是单个贴图或者是合图的贴图
* @param rect 如果是单个贴图则不需要传裁剪矩形,合图中的贴图请传入spriteFrame.rect用来确定偏移位置和裁剪大小
* @returns Uint8Array 按rgba排列
*/
getPixels(sp: cc.Sprite, rect?: cc.Rect): Uint8Array {
let width = sp.getComponent(cc.UITransform).width;
let height = sp.getComponent(cc.UITransform).height;
const gfxTexture = sp.spriteFrame.getGFXTexture();
if (!gfxTexture) {
return null;
}
const bufferViews: ArrayBufferView[] = [];
const regions: cc.gfx.BufferTextureCopy[] = [];
const region0 = new cc.gfx.BufferTextureCopy();
region0.texOffset.x = rect?.x || 0;
region0.texOffset.y = rect?.y || 0;
region0.texExtent.width = width;
region0.texExtent.height = height;
regions.push(region0);
const buffer = new Uint8Array(width * height * 4);
bufferViews.push(buffer);
cc.director.root?.device.copyTextureToBuffers(gfxTexture, bufferViews, regions)
return buffer;
}
将像素信息设置给精灵
this._drawTexture2D = new cc.Texture2D();
this._drawTexture2D.reset({ width: this._width, height: this._height, format: this.drawImg.spriteFrame.texture.getPixelFormat() });
this._drawTexture2D.uploadData(this._drawTexuture);
this.drawImg.spriteFrame.texture = this._drawTexture2D;