一文搞定ArkUI所有图片加载场景:收藏这一篇就够了

图片(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%')
  }
}

免费考取 鸿蒙开发者认证 。欢迎留言、评论、本人整理了学习、考试相关资料免费送。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值