图片(Image)
在页面中显示图片是很常见的场景,下面介绍一下图片组件(Image
)的使用。
Image
支持多种图片类型加载。大致可分为Resources资源、本地资源、网络资源、媒体库资源、多媒体像素图、可绘制描述符、矢量图。
加载Resources资源
- 图片存放在
resources/base/media
目录下
使用Image($r('app.media.xxx'))
形式引用,其中xxx
为图片名称(不需要带扩展名)。
Image($r('app.media.image'))
.width(200)
.height(100)
- 图片存放在
resources/rawfile
目录下
使用Image($rawfile('xxx.png'))
形式引用,其中xxx
为图片名称(需要带扩展名)。
Image($rawfile('image.jpeg'))
.width(200)
.height(100)
加载本地图片
图片还可以直接存放在ets
目录下,比如ets/image/xxx.png
,此时加载图片代码如下:
Image("/image/image.jpeg")
.width(200)
.height(100)
加载网络图片
引入网络图片需申请权限ohos.permission.INTERNET
,在module.json5
文件中加入如下代码
"requestPermissions": [
{
"name":"ohos.permission.INTERNET"
}
],
此时,Image
组件的src
参数为网络图片的链接。
Image('https://www.example.com/example.JPG') // 实际使用时请替换为真实地址
加载像素图
PixelMap
是图片解码后的像素图,以下示例将加载的网络图片返回的数据解码成PixelMap
格式,再显示在Image
组件上。
如图所示,点击按钮时从网络加载像素图
代码如下
import { http } from '@kit.NetworkKit';
import { image } from '@kit.ImageKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct HttpExample {
outData: http.HttpResponse | undefined = undefined;
code: http.ResponseCode | number | undefined = undefined;
@State image: PixelMap | undefined = undefined; //创建PixelMap状态变量。
//加载多媒体像素图
getPixeMap() {
http.createHttp().request('https://file.atomgit.com/uploads/user/1704857786989_8994.jpeg', //请填写一个具体的网络图片地址。
(error: BusinessError, data: http.HttpResponse) => {
if (error) {
console.error('hello http request failed with. Code: ${error.code}, message: ${error.message}');
return;
}
this.outData = data;
//将网络地址成功返回的数据,编码转码成pixelMap的图片格式。
if (http.ResponseCode.OK === this.outData.responseCode) {
let imageData: ArrayBuffer = this.outData.result as ArrayBuffer;
let imageSource: image.ImageSource = image.createImageSource(imageData);
let options: image.DecodingOptions = {
'desiredPixelFormat': image.PixelMapFormat.RGBA_8888,
};
imageSource.createPixelMap(options).then((pixelMap: PixelMap) => {
this.image = pixelMap;
});
}
})
}
build() {
Column({space:10}) {
Button("点击加载像素图").onClick(() => {
this.getPixeMap()
})
//显示图片
Image(this.image)
.width(200)
.height(100)
.objectFit(ImageFit.Auto)
.borderWidth(1)
}.width("100%")
.height("100%")
}
}
加载矢量图
Image
组件可显示矢量图(SVG
格式的图片),如果SVG
图片没有原始大小,需要给Image
组件设置宽高,否则不显示。
SVG
格式的图片可以使用fillColor
属性改变图片的绘制颜色。
Image($r('app.media.cloud'))
.width(50)
.fillColor(Color.Blue)
原始图片
设置绘制颜色后的SVG图片
加载多媒体库图片
如下图所示,有时候我们需要从系统图库中选择图片然后加载到页面上。
从媒体库获取的uri
格式通常为:file://media/Photo/6/xxxx.jpg
,此路径需要通过图片选择器获取。通过Image(uri)
可以将图片加载到页面上。
如图所示:点击按钮时打开图片选择器,选择多张图片加载到页面上。
代码如下
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
@State imgDatas: string[] = [];
// 获取照片url集
getAllImg() {
try {
let photoSelectOptions:photoAccessHelper.PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
photoSelectOptions.maxSelectNumber = 5;
let photoPicker:photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
photoPicker.select(photoSelectOptions).then((PhotoSelectResult:photoAccessHelper.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}`); }
}
// 使用imgDatas的url加载图片。
build() {
Column() {
Button("加载多媒体库图片").onClick(()=>{
this.getAllImg()
})
Grid() {
ForEach(this.imgDatas, (item:string) => {
GridItem() {
Image(item)
.width(100)
.height(100)
.objectFit(ImageFit.Fill)
}
}, (item:string):string => JSON.stringify(item))
}
}.width('100%').height('100%')
}
}
免费考取 鸿蒙开发者认证 。欢迎留言、评论、本人整理了学习、考试相关资料免费送。