显示图片(Image)

2024-01-25 13:21 更新

开发者经常需要在应用中显示一些图片,例如:按钮中的icon、网络图片、本地图片等。在应用中显示图片需要使用Image组件实现,Image支持多种图片格式,包括png、jpg、bmp、svg和gif,具体用法请参考Image组件。

Image通过调用接口来创建,接口调用形式如下:

  1. Image(src: string | Resource | media.PixelMap)

该接口通过图片数据源获取图片,支持本地图片和网络图片的渲染展示。其中,src是图片的数据源,加载方式请参考加载图片资源

加载图片资源

Image支持加载存档图、多媒体像素图两种类型。

存档图类型数据源

存档图类型的数据源可以分为本地资源、网络资源、Resource资源、媒体库资源和base64。

  • 本地资源

    创建文件夹,将本地图片放入ets文件夹下的任意位置。

    Image组件引入本地图片路径,即可显示图片(根目录为ets文件夹)。

    1. Image('images/view.jpg')
    2. .width(200)
  • 网络资源

    引入网络图片需申请权限ohos.permission.INTERNET,具体申请方式请参考权限申请声明此时,Image组件的src参数为网络图片的链接。

    1. Image('https://www.example.com/example.JPG') // 实际使用时请替换为真实地址
  • Resource资源

    使用资源格式可以跨包/跨模块引入图片,resources文件夹下的图片都可以通过$r资源接口读取到并转换到Resource格式。

    图1 resources

    调用方式:

    1. Image($r('app.media.icon'))

    还可以将图片放在rawfile文件夹下。

    图2 rawfile

    调用方式:

    1. Image($rawfile('snap'))
  • 媒体库file://data/storage

    支持file://路径前缀的字符串,用于访问通过媒体库提供的图片路径。

    1. 调用接口获取图库的照片url。
      1. import picker from '@ohos.file.picker';
      2. @Entry
      3. @Component
      4. struct Index {
      5. @State imgDatas: string[] = [];
      6. // 获取照片url集
      7. getAllImg() {
      8. let result = new Array<string>();
      9. try {
      10. let PhotoSelectOptions = new picker.PhotoSelectOptions();
      11. PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
      12. PhotoSelectOptions.maxSelectNumber = 5;
      13. let photoPicker = new picker.PhotoViewPicker();
      14. photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => {
      15. this.imgDatas = PhotoSelectResult.photoUris;
      16. console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
      17. }).catch((err) => {
      18. console.error(`PhotoViewPicker.select failed with. Code: ${err.code}, message: ${err.message}`);
      19. });
      20. } catch (err) {
      21. console.error(`PhotoViewPicker failed with. Code: ${err.code}, message: ${err.message}`); }
      22. }
      23. // aboutToAppear中调用上述函数,获取图库的所有图片url,存在imgDatas中
      24. async aboutToAppear() {
      25. this.getAllImg();
      26. }
      27. // 使用imgDatas的url加载图片。
      28. build() {
      29. Column() {
      30. Grid() {
      31. ForEach(this.imgDatas, item => {
      32. GridItem() {
      33. Image(item)
      34. .width(200)
      35. }
      36. }, item => JSON.stringify(item))
      37. }
      38. }.width('100%').height('100%')
      39. }
      40. }
    2. 从媒体库获取的url格式通常如下。
      1. Image('file://media/Photos/5')
      2. .width(200)
  • base64

    路径格式为data:image/[png|jpeg|bmp|webp];base64,[base64 data],其中[base64 data]为Base64字符串数据。

    Base64格式字符串可用于存储图片的像素数据,在网页上使用较为广泛。

多媒体像素图

PixelMap是图片解码后的像素图,具体用法请参考图片开发指导。以下示例将加载的网络图片返回的数据解码成PixelMap格式,再显示在Image组件上,

  1. 创建PixelMap状态变量。
    1. @State image: PixelMap = undefined;
  2. 引用多媒体。

    请求网络图片请求,解码编码PixelMap。

    1. 引用网络权限与媒体库权限。
      1. import http from '@ohos.net.http';
      2. import ResponseCode from '@ohos.net.http';
      3. import image from '@ohos.multimedia.image';
    2. 填写网络图片地址。
      1. http.createHttp().request("https://www.example.com/xxx.png",
      2. (error, data) => {
      3. if (error){
      4. console.error(`http reqeust failed with. Code: ${error.code}, message: ${error.message}`);
      5. } else {
      6. }
      7. }
      8. )
    3. 将网络地址成功返回的数据,编码转码成pixelMap的图片格式。
      1. let code = data.responseCode;
      2. if (ResponseCode.ResponseCode.OK === code) {
      3. let res: any = data.result
      4. let imageSource = image.createImageSource(res);
      5. let options = {
      6. alphaType: 0, // 透明度
      7. editable: false, // 是否可编辑
      8. pixelFormat: 3, // 像素格式
      9. scaleMode: 1, // 缩略值
      10. size: { height: 100, width: 100}
      11. } // 创建图片大小
      12. imageSource.createPixelMap(options).then((pixelMap) => {
      13. this.image = pixelMap
      14. })
      15. }
    4. 显示图片。
      1. Button("获取网络图片")
      2. .onClick(() => {
      3. this.httpRequest()
      4. })
      5. Image(this.image).height(100).width(100)

显示矢量图

Image组件可显示矢量图(svg格式的图片),支持的svg标签为:svg、rect、circle、ellipse、path、line、polyline、polygon和animate。

svg格式的图片可以使用fillColor属性改变图片的绘制颜色。

  1. Image($r('app.media.cloud')).width(50)
  2. .fillColor(Color.Blue)
图3 原始图片
图4 设置绘制颜色后的svg图片

添加属性

给Image组件设置属性可以使图片显示更灵活,达到一些自定义的效果。以下是几个常用属性的使用示例,完整属性信息详见Image

设置图片缩放类型

通过objectFit属性使图片缩放到高度和宽度确定的框内。

  1. @Entry
  2. @Component
  3. struct MyComponent {
  4. scroller: Scroller = new Scroller()
  5. build() {
  6. Scroll(this.scroller) {
  7. Row() {
  8. Image($r('app.media.img_2')).width(200).height(150)
  9. .border({ width: 1 })
  10. .objectFit(ImageFit.Contain).margin(15) // 保持宽高比进行缩小或者放大,使得图片完全显示在显示边界内。
  11. .overlay('Contain', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  12. Image($r('app.media.ic_img_2')).width(200).height(150)
  13. .border({ width: 1 })
  14. .objectFit(ImageFit.Cover).margin(15)
  15. // 保持宽高比进行缩小或者放大,使得图片两边都大于或等于显示边界。
  16. .overlay('Cover', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  17. Image($r('app.media.img_2')).width(200).height(150)
  18. .border({ width: 1 })
  19. // 自适应显示。
  20. .objectFit(ImageFit.Auto).margin(15)
  21. .overlay('Auto', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  22. }
  23. Row() {
  24. Image($r('app.media.img_2')).width(200).height(150)
  25. .border({ width: 1 })
  26. .objectFit(ImageFit.Fill).margin(15)
  27. // 不保持宽高比进行放大缩小,使得图片充满显示边界。
  28. .overlay('Fill', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  29. Image($r('app.media.img_2')).width(200).height(150)
  30. .border({ width: 1 })
  31. // 保持宽高比显示,图片缩小或者保持不变。
  32. .objectFit(ImageFit.ScaleDown).margin(15)
  33. .overlay('ScaleDown', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  34. Image($r('app.media.img_2')).width(200).height(150)
  35. .border({ width: 1 })
  36. // 保持原有尺寸显示。
  37. .objectFit(ImageFit.None).margin(15)
  38. .overlay('None', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  39. }
  40. }
  41. }
  42. }

图片插值

当原图分辨率较低并且放大显示时,图片会模糊出现锯齿。这时可以使用interpolation属性对图片进行插值,使图片显示得更清晰。

  1. @Entry
  2. @Component
  3. struct Index {
  4. build() {
  5. Column() {
  6. Row() {
  7. Image($r('app.media.grass'))
  8. .width('40%')
  9. .interpolation(ImageInterpolation.None)
  10. .borderWidth(1)
  11. .overlay("Interpolation.None", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  12. .margin(10)
  13. Image($r('app.media.grass'))
  14. .width('40%')
  15. .interpolation(ImageInterpolation.Low)
  16. .borderWidth(1)
  17. .overlay("Interpolation.Low", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  18. .margin(10)
  19. }.width('100%')
  20. .justifyContent(FlexAlign.Center)
  21. Row() {
  22. Image($r('app.media.grass'))
  23. .width('40%')
  24. .interpolation(ImageInterpolation.Medium)
  25. .borderWidth(1)
  26. .overlay("Interpolation.Medium", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  27. .margin(10)
  28. Image($r('app.media.grass'))
  29. .width('40%')
  30. .interpolation(ImageInterpolation.High)
  31. .borderWidth(1)
  32. .overlay("Interpolation.High", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  33. .margin(10)
  34. }.width('100%')
  35. .justifyContent(FlexAlign.Center)
  36. }
  37. .height('100%')
  38. }
  39. }

设置图片重复样式

通过objectRepeat属性设置图片的重复样式方式,重复样式请参考ImageRepeat枚举说明。

  1. @Entry
  2. @Component
  3. struct MyComponent {
  4. build() {
  5. Column({ space: 10 }) {
  6. Row({ space: 5 }) {
  7. Image($r('app.media.ic_public_favor_filled_1'))
  8. .width(110)
  9. .height(115)
  10. .border({ width: 1 })
  11. .objectRepeat(ImageRepeat.XY)
  12. .objectFit(ImageFit.ScaleDown)
  13. // 在水平轴和竖直轴上同时重复绘制图片
  14. .overlay('ImageRepeat.XY', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  15. Image($r('app.media.ic_public_favor_filled_1'))
  16. .width(110)
  17. .height(115)
  18. .border({ width: 1 })
  19. .objectRepeat(ImageRepeat.Y)
  20. .objectFit(ImageFit.ScaleDown)
  21. // 只在竖直轴上重复绘制图片
  22. .overlay('ImageRepeat.Y', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  23. Image($r('app.media.ic_public_favor_filled_1'))
  24. .width(110)
  25. .height(115)
  26. .border({ width: 1 })
  27. .objectRepeat(ImageRepeat.X)
  28. .objectFit(ImageFit.ScaleDown)
  29. // 只在水平轴上重复绘制图片
  30. .overlay('ImageRepeat.X', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  31. }
  32. }.height(150).width('100%').padding(8)
  33. }
  34. }

设置图片渲染模式

通过renderMode属性设置图片的渲染模式为原色或黑白。

  1. @Entry
  2. @Component
  3. struct MyComponent {
  4. build() {
  5. Column({ space: 10 }) {
  6. Row({ space: 50 }) {
  7. Image($r('app.media.example'))
  8. // 设置图片的渲染模式为原色
  9. .renderMode(ImageRenderMode.Original)
  10. .width(100)
  11. .height(100)
  12. .border({ width: 1 })
  13. // overlay是通用属性,用于在组件上显示说明文字
  14. .overlay('Original', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  15. Image($r('app.media.example'))
  16. // 设置图片的渲染模式为黑白
  17. .renderMode(ImageRenderMode.Template)
  18. .width(100)
  19. .height(100)
  20. .border({ width: 1 })
  21. .overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
  22. }
  23. }.height(150).width('100%').padding({ top: 20,right: 10 })
  24. }
  25. }

设置图片解码尺寸

通过sourceSize属性设置图片解码尺寸,降低图片的分辨率。

原图尺寸为1280*960,该示例将图片解码为150*150和400*400。

  1. @Entry
  2. @Component
  3. struct Index {
  4. build() {
  5. Column() {
  6. Row({ space: 20 }) {
  7. Image($r('app.media.example'))
  8. .sourceSize({
  9. width: 150,
  10. height: 150
  11. })
  12. .objectFit(ImageFit.ScaleDown)
  13. .width('25%')
  14. .aspectRatio(1)
  15. .border({ width: 1 })
  16. .overlay('width:150 height:150', { align: Alignment.Bottom, offset: { x: 0, y: 40 } })
  17. Image($r('app.media.example'))
  18. .sourceSize({
  19. width: 400,
  20. height: 400
  21. })
  22. .objectFit(ImageFit.ScaleDown)
  23. .width('25%')
  24. .aspectRatio(1)
  25. .border({ width: 1 })
  26. .overlay('width:400 height:400', { align: Alignment.Bottom, offset: { x: 0, y: 40 } })
  27. }.height(150).width('100%').padding(20)
  28. }
  29. }
  30. }

为图片添加滤镜效果

通过colorFilter修改图片的像素颜色,为图片添加滤镜。

  1. @Entry
  2. @Component
  3. struct Index {
  4. build() {
  5. Column() {
  6. Row() {
  7. Image($r('app.media.example'))
  8. .width('40%')
  9. .margin(10)
  10. Image($r('app.media.example'))
  11. .width('40%')
  12. .colorFilter(
  13. [1, 1, 0, 0, 0,
  14. 0, 1, 0, 0, 0,
  15. 0, 0, 1, 0, 0,
  16. 0, 0, 0, 1, 0])
  17. .margin(10)
  18. }.width('100%')
  19. .justifyContent(FlexAlign.Center)
  20. }
  21. }
  22. }

同步加载图片

一般情况下,图片加载流程会异步进行,以避免阻塞主线程,影响UI交互。但是特定情况下,图片刷新时会出现闪烁,这时可以使用syncLoad属性,使图片同步加载,从而避免出现闪烁。不建议图片加载较长时间时使用,会导致页面无法响应。

  1. Image($r('app.media.icon'))
  2. .syncLoad(true)

事件调用

通过在Image组件上绑定onComplete事件,图片加载成功后可以获取图片的必要信息。如果图片加载失败,也可以通过绑定onError回调来获得结果。

  1. @Entry
  2. @Component
  3. struct MyComponent {
  4. @State widthValue: number = 0
  5. @State heightValue: number = 0
  6. @State componentWidth: number = 0
  7. @State componentHeight: number = 0
  8. build() {
  9. Column() {
  10. Row() {
  11. Image($r('app.media.ic_img_2'))
  12. .width(200)
  13. .height(150)
  14. .margin(15)
  15. .onComplete(msg => {
  16. if(msg){
  17. this.widthValue = msg.width
  18. this.heightValue = msg.height
  19. this.componentWidth = msg.componentWidth
  20. this.componentHeight = msg.componentHeight
  21. }
  22. })
  23. // 图片获取失败,打印结果
  24. .onError(() => {
  25. console.info('load image fail')
  26. })
  27. .overlay('\nwidth: ' + String(this.widthValue) + ', height: ' + String(this.heightValue) + '\ncomponentWidth: ' + String(this.componentWidth) + '\ncomponentHeight: ' + String(this.componentHeight), {
  28. align: Alignment.Bottom,
  29. offset: { x: 0, y: 60 }
  30. })
  31. }
  32. }
  33. }
  34. }

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号