使用drawing.canvas绘制本地Image时,执行到canvas.drawImage(this.pixelMap, 0, 0);时报出参数错误问题
async draw(context : DrawContext) {
const canvas = context.canvas;
// 获取resourceManager资源管理
const resourceMgr : resourceManager.ResourceManager = this.comContext.resourceManager;
await resourceMgr.getRawFd('ic_in_selected_red.png').then(async (rawFileDescriptor : resourceManager.RawFileDescriptor) => {
console.log("Succeeded in getting RawFd")
const imageSource : image.ImageSource = image.createImageSource(rawFileDescriptor)
await imageSource.createPixelMap().then((pixelMap: image.PixelMap) => {
this.pixelMap = pixelMap
console.log("Succeeded in creating PixelMap")
}).catch((err : BusinessError) => {
console.error("Failed to creating PixelMap")
});
}).catch((err : BusinessError) => {
console.error("Failed to get RawFd")
});
console.error("draw image")
try {
if (this.pixelMap != null) {
canvas.drawImage(this.pixelMap, 0, 0);
}
} catch (e) {
console.error("draw image error=" + e)
}
}
这个时序影响着参数调用?我现在通过await控制时序了,最后调用canvas.drawImage(this.pixelMap, 0, 0),也是返回Error: Invalid params.
可以基于上面的代码调试(ps 正常业务内我们加载一张图片不会放在aboutToAppear中)
问题原因:异步绘制时,在drawImage调用前,arkui就已经调用了drawing的canvas的ResetCanvas接口,导致对应的canvas被释放了而无法绘制drawImage。
解决方案:提前把pixelmap保存起来,等绘制的时候直接绘制pixelmap。比如在aboutToAppear生命周期函数里面就去加载图片,创建pixelmap。