HarmonyOS NEXT实战:网络图片加载和失败占位图

3 阅读2分钟

##HarmonyOS Next实战##HarmonyOS应用开发##教育##

目标:网络图片加载时,显示加载图,加载完毕后显示网络图片,加载失败则显示加载失败的占位图。

前提:需要申请权限ohos.permission.INTERNET。

实现思路:

  1. 通过Image显示图片。
  2. 通过Image的alt设置加载图。
  3. 通过Image的onError事件获取加载失败的状态。
  4. 根据加载状态显示对应的占位图。

接口说明

alt(value: string | Resource | PixelMap)

设置图片加载时显示的占位图。当组件的参数类型为AnimatedDrawableDescriptor时设置该属性不生效。 说明:加载时显示的占位图,支持本地图片(png、jpg、bmp、svg、gif和heif类型),支持PixelMap类型图片,不支持网络图片。(默认值:null)

onComplete事件

onComplete(callback: (event?: { width: number, height: number, componentWidth: number, componentHeight: number, loadingStatus: number,contentWidth: number, contentHeight: number, contentOffsetX: number, contentOffsetY: number }) => void)

图片数据加载成功和解码成功时均触发该回调,返回成功加载的图片尺寸。 当组件的参数类型为AnimatedDrawableDescriptor时该事件不触发。

onError事件

onError(callback: ImageErrorCallback)

图片加载异常时触发该回调。 当组件的参数类型为AnimatedDrawableDescriptor时该事件不触发。 说明:图片加载异常时触发的回调。建议开发者使用此回调,可快速确认图片加载失败时的具体原因。

ImageErrorCallback: 图片加载异常时触发的回调。 当组件的参数类型为AnimatedDrawableDescriptor时该事件不触发。

onFinish事件

onFinish(event: () => void)

当加载的源文件为带动效的svg格式图片时,svg动效播放完成时会触发这个回调。如果动效为无限循环动效,则不会触发这个回调。 仅支持svg格式的图片。当组件的参数类型为AnimatedDrawableDescriptor时该事件不触发。

aspectRatio接口

aspectRatio(value: number)

指定当前组件的宽高比,aspectRatio=width/height。 仅设置width、aspectRatio时,height=width/aspectRatio。 仅设置height、aspectRatio时,width=height*aspectRatio。 同时设置width、height和aspectRatio时,height不生效,height=width/aspectRatio。 设置aspectRatio属性后,组件宽高会受父组件内容区大小限制。

实战代码:

@Entry
@Component
struct ImagePlaceholderPage {
  imageSrc: string = 'https://c-ssl.dtstatic.com/uploads/blog/202311/27/0GSZv1oh0ePwpE.thumb.400_0.jpeg'
  @State loadingSuccess: boolean = true

  build() {
    Column({ space: 10 }) {
      Text('图片占位符')
      this.buildImage(this.imageSrc)
    }
    .width('100%')
    .height('100%')
    .padding(20)
  }

  @Builder
  buildImage(src: string) {
    Row() {
      if (this.loadingSuccess) {
        Image(src)
          .width('100%')// .alt($r('app.media.rays'))
          .onComplete(() => {
            //图片数据加载成功和解码成功时均触发该回调
            this.loadingSuccess = true
          })
          .onError(() => {
            //图片加载异常时触发该回调。
            this.loadingSuccess = false
          })
          .onFinish(() => {
            //当加载的源文件为带动效的svg格式图片时,svg动效播放完成时会触发这个回调。如果动效为无限循环动效,则不会触发这个回调。
          })
      } else {
        //图片加载失败的占位图
        Column({ space: 10 }) {
          SymbolGlyph($r('sys.symbol.exclamationmark_circle'))
            .fontSize(30)
            .renderingStrategy(SymbolRenderingStrategy.SINGLE)
            .fontColor([Color.Gray])
          Text('图片加载失败')
            .fontColor(Color.Gray)
        }
      }
    }
    .width('100%')
    .justifyContent(FlexAlign.Center)
    .borderRadius(6)
    .backgroundColor('#EEEEEE')
    .aspectRatio(1)
    .clip(true)
  }
}