HarmonyOS鸿蒙Next中Image组件如何加载其他模块下的本地图片

HarmonyOS鸿蒙Next中Image组件如何加载其他模块下的本地图片 举例,有2个模块,分别模块1、模块2 模块1下使用Image组件,加载自身模块下的本地图片,可以使用路径Image($r(‘app.media.ic_ok’))。但是我有需求,想在模块1下引用模块2资源的本地图片。不知道代码该如何实现?

3 回复

跨HAP/HSP包应用资源:

bundle相同,跨module访问

方式一:通过createModuleContext(moduleName)接口创建同应用中不同module的上下文,获取resourceManager对象后,调用不同接口访问不同资源。

getContext(this).createModuleContext(moduleName).resourceManager.getStringByNameSync('app.string.XXX')

方式二:通过$r$rawfile引用资源(api12支持的能力)。

  1. [hsp].type.name获取资源。其中,hsp为hsp模块名,type为资源类型,name为资源名称
Text($r('[hsp].string.test_string'))
  .fontSize($r('[hsp].float.font_size'))
  .fontColor($r('[hsp].color.font_color'))
 Image($rawfile('[hsp].oneFile/twoFile/icon.png'))
  1. 使用变量获取资源
@Entry
@Component
struct Index {
 text: string = '[hsp].string.test_string';
 fontSize: string = '[hsp].float.font_size';
 fontColor: string = '[hsp].color.font_color';
 image: string = '[hsp].media.string';
 rawfile: string = '[hsp].icon.png';
 
 build() {
   Row() {
     Text($r(this.text))
       .fontSize($r(this.fontSize))
       .fontColor($r(this.fontColor))

     Image($r(this.image))

     Image($rawfile(this.rawfile))
   }
 }
}

说明:hsp包名必须写在[]内,"rawfile"下有多层目录,需要从"rawfile"下面第一个目录开始写,如$rawfile('[hsp].oneFile/twoFile/icon.png'),使用$r$rawfile跨包访问HSP包资源无法提供编译时的资源校验,需要开发者自行保证使用资源存在于对应包中。

更多关于HarmonyOS鸿蒙Next中Image组件如何加载其他模块下的本地图片的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙)Next中,Image组件加载其他模块下的本地图片可以通过使用ResourceManager来实现。首先,确保目标模块的图片资源已经正确放置在resources目录下。然后,使用ResourceManagergetResource方法获取图片资源的路径或资源ID,并将其传递给Image组件的src属性。

例如,假设有一个模块moduleA,其中包含一张图片image.png,路径为moduleA/resources/base/media/image.png。在另一个模块moduleB中,可以通过以下代码加载这张图片:

import { ResourceManager } from '@ohos.resourceManager';
import { Image } from '@ohos.arkui';

// 获取ResourceManager实例
let resourceManager = ResourceManager.getResourceManager();

// 获取图片资源的路径或资源ID
let imagePath = resourceManager.getResource('moduleA', 'media/image.png');

// 将图片路径传递给Image组件
Image.create(imagePath);

需要注意的是,ResourceManager的使用需要确保模块之间的依赖关系已经正确配置,并且在module.json5中声明了所需的资源访问权限。

在HarmonyOS鸿蒙Next中,如果Image组件需要加载其他模块下的本地图片,可以使用资源管理器的绝对路径进行引用。首先,确保图片资源已添加到对应模块的resources目录下。然后,在代码中使用$r函数引用图片资源,例如:$r('app.media.image_name'),其中app是模块名,media是资源类型,image_name是图片文件名。这样,Image组件即可正确加载跨模块的本地图片。

回到顶部