有大佬知道使用createPixelMap构建pixelmap,最终展示的颜色与期望不符合是怎么回事吗?

下面代码,期望绘制蓝色,最终展示为红色

let length = 600 * 600 * 4; 
let buffer = new Uint8Array(length); 
for (let index = 0; index < length; ) { 
  buffer[index] = 0x00; //R 
  buffer[index + 1] = 0x00; //G 
  buffer[index + 2] = 0xff; //B 
  buffer[index + 3] = 0xff; //A 
  index = index + 4; 
} 
let opts: image.InitializationOptions = { 
  pixelFormat: image.PixelMapFormat.RGBA_8888, 
  size: { 
    height: 600, 
    width: 600 
  } 
} 
image.createPixelMap(buffer.buffer, opts).then((pixelMap) => { 
  this.context.drawImage(pixelMap, 0, 0); 
})
阅读 507
1 个回答

如果想要将图像绘制为不透明的蓝色,可以将Alpha通道的值设置为255。在代码中,已经将蓝色通道设置为 0xff,Alpha通道也设置为 0xff,这意味着颜色已经是不透明的蓝色。
但代码中有一个错误,在 for 循环中,index 应该每次增加像素的字节数,也就是4,但代码中 index 只增加了1。这会导致循环中的代码重复设置同一个像素的颜色值,而不是按顺序设置每个像素。

let length = 600 * 600 * 4;
let buffer = new Uint8Array(length);
for (let index = 0; index < length; index += 4) {
  buffer[index] = 0x00;     // R
  buffer[index + 1] = 0x00; // G
  buffer[index + 2] = 0xff; // B
  buffer[index + 3] = 0xff; // A (不透明)
}

let opts = {
  pixelFormat: image.PixelMapFormat.RGBA_8888,
  size: {
    height: 600,
    width: 600
  }
};
image.createPixelMap(buffer.buffer, opts).then((pixelMap) => {
  this.context.drawImage(pixelMap, 0, 0);
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进