HarmonyOS鸿蒙Next中选择本地的图片如何显示在Image组件上
HarmonyOS鸿蒙Next中选择本地的图片如何显示在Image组件上
这边选择的图片路径是这样的
/Photo/6/IMG_1712626998_005
如何把选择处的这个路径的图片显示在Image组件上呢?
3 回复
import picker from '@ohos.file.picker';
import { BusinessError } from '@ohos.base';
@Entry
@Component
struct Index {
@State imgDatas: string[] = [];
// 获取照片url集
getAllImg() {
try {
let PhotoSelectOptions:picker.PhotoSelectOptions = new picker.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
PhotoSelectOptions.maxSelectNumber = 5;
let photoPicker:picker.PhotoViewPicker = new picker.PhotoViewPicker();
photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult:picker.PhotoSelectResult) => {
this.imgDatas = PhotoSelectResult.photoUris;
console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
}).catch((err:Error) => {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
console.error(`PhotoViewPicker.select failed with. Code: ${code}, message: ${message}`);
});
} catch (err) {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
console.error(`PhotoViewPicker failed with. Code: ${code}, message: ${message}`);
}
}
// aboutToAppear中调用上述函数,获取图库的所有图片url,存在imgDatas中
async aboutToAppear() {
this.getAllImg();
}
// 使用imgDatas的url加载图片。
build() {
Column() {
Grid() {
ForEach(this.imgDatas, (item:string) => {
GridItem() {
Image(item)
.width(200)
}
}, (item:string):string => JSON.stringify(item))
}
}.width('100%').height('100%')
}
}
更多关于HarmonyOS鸿蒙Next中选择本地的图片如何显示在Image组件上的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS Next中,若要在Image
组件上显示本地图片,可以使用ResourceManager
来加载资源。首先,将图片文件放置在项目的resources
目录下,例如resources/base/media/
。然后,在代码中通过$r('app.media.图片文件名')
的方式引用图片资源,并将其赋值给Image
组件的src
属性。
示例代码如下:
import { Image } from '@ohos.arkui';
import { ResourceManager } from '@ohos.resource';
@Entry
@Component
struct MyComponent {
build() {
Column() {
Image($r('app.media.my_image'))
.width(100)
.height(100)
}
}
}
其中,my_image
为图片文件名(无需扩展名)。通过这种方式,Image
组件会加载并显示指定的本地图片。注意,图片文件需符合HarmonyOS的资源管理规范,且路径和文件名需正确无误。
在HarmonyOS鸿蒙Next中,可以通过Image
组件显示本地图片。首先,将图片资源放置在resources/base/media
目录下。然后,在布局文件中使用Image
组件,并通过ohos:image_src
属性指定图片路径,例如ohos:image_src="$media:your_image"
。代码示例如下:
<Image
ohos:width="match_content"
ohos:height="match_content"
ohos:image_src="$media:your_image"/>