HarmonyOS鸿蒙Next中如何在Native通过图片名称获取rawFile文件并设置到Image上
HarmonyOS鸿蒙Next中如何在Native通过图片名称获取rawFile文件并设置到Image上
_env = env;
_nativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, arg);
RawFile *rawFile = OH_ResourceManager_OpenRawFile(_nativeResMgr, src.c_str());
ArkUI_DrawableDescriptor* drawableDescriptor = nullptr;
if (rawFile != NULL) {
// 获取文件大小,并读取数据。
long len = OH_ResourceManager_GetRawFileSize(rawFile);
uint8_t *data = static_cast<uint8_t *>(malloc(len));
int res = OH_ResourceManager_ReadRawFile(rawFile, data, len);
OhosImageSource imageSource_c;
imageSource_c.buffer = data;
imageSource_c.bufferSize = len;
OhosImageSourceOps ops{};
napi_value imageSource;
napi_value pixelMap;
// 用读取到的Raw数据创建ImageSource。
int32_t ret = OH_ImageSource_Create(_env, &imageSource_c, &ops, &imageSource);
// 初始化native层的ImageSource。
ImageSourceNative *imageSourceNative_c = OH_ImageSource_InitNative(_env, imageSource);
OhosImageDecodingOps decodingOps{};
// 创建pixelMap。
OH_ImageSource_CreatePixelMap(imageSourceNative_c, &decodingOps, &pixelMap);
//ArkUI_DrawableDescriptor *descriptor = OH_ArkUI_DrawableDescriptor_CreateFromPixelMap(pixelMap);
// 映射到 Native - 使用正确的API调用
ret = OH_ArkUI_GetDrawableDescriptorFromNapiValue(_env, pixelMap, &drawableDescriptor);
// 处理完毕,释放native层资源。
OH_ImageSource_Release(imageSourceNative_c);
OH_ResourceManager_CloseRawFile(rawFile);
// 释放临时数据
free(data);
}
return drawableDescriptor;
目前OH_ArkUI_GetDrawableDescriptorFromNapiValue 会有异常…
更多关于HarmonyOS鸿蒙Next中如何在Native通过图片名称获取rawFile文件并设置到Image上的实战教程也可以访问 https://www.itying.com/category-93-b0.html
3 回复
你好,因为没有具体说是哪方面异常,所以列举几个异常可能原因看看是否是其中之一:
- 参数类型不匹配:传入的napi_value参数未正确指向ArkTS侧创建的NodeContent对象,或ArkUI_DrawableDescriptor指针未正确初始化。
- 资源格式不支持:该接口支持的资源类型包括png、jpg、bmp、svg、gif、webp、astc、sut。
- 内存管理问题:未正确释放ArkUI_DrawableDescriptor指针分配的内存,或重复释放同一指针。
更多关于HarmonyOS鸿蒙Next中如何在Native通过图片名称获取rawFile文件并设置到Image上的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS Next中,通过Native层获取rawFile图片并设置到Image组件时,建议采用以下优化方案:
-
使用
OH_ArkUI_DrawableDescriptor_CreateFromPixelMap替代OH_ArkUI_GetDrawableDescriptorFromNapiValue,该API专为PixelMap到DrawableDescriptor转换设计。 -
关键代码调整:
// 替换以下注释代码
// ArkUI_DrawableDescriptor *descriptor = OH_ArkUI_DrawableDescriptor_CreateFromPixelMap(pixelMap);
// 改为直接调用(移除napi_value中间转换):
ArkUI_DrawableDescriptor* drawableDescriptor = OH_ArkUI_DrawableDescriptor_CreateFromPixelMap(pixelMap);
- 确保资源路径正确:
- rawFile路径应为
resources/rawfile/目录下的相对路径 - 图片名称需包含完整扩展名(如
.png)
- 内存管理优化:
- 在DrawableDescriptor使用完毕后调用
OH_ArkUI_DrawableDescriptor_Release - 添加NULL指针检查,确保资源释放
该方案通过直接API调用规避了napi_value转换环节的潜在问题,提高了代码稳定性和执行效率。


