HarmonyOS软件开发:ArkTS常见组件之自定义弹窗 (CustomDialog)和显示图片 (Image)

27 篇文章 0 订阅
27 篇文章 0 订阅

CustomDialog是自定义弹窗,可用于广告、中奖、警告、软件更新等与用户交互响应操作。开发者可以通过CustomDialogController类显示自定义弹窗。

创建自定义弹窗

  1. 使用@CustomDialog装饰器装饰自定义弹窗。

  2. @CustomDialog装饰器用于装饰自定义弹框,此装饰器内进行自定义内容(也就是弹框内容)。

    @CustomDialog
    struct CustomDialogExample {
      controller: CustomDialogController = new CustomDialogController({
        builder: CustomDialogExample({}),
      })
    
      build() {
        Column() {
          Text('我是内容')
            .fontSize(20)
            .margin({ top: 10, bottom: 10 })
        }
      }
    }
  3. 创建构造器,与装饰器呼应相连。

     @Entry
     @Component
     struct CustomDialogUser {
       dialogController: CustomDialogController = new CustomDialogController({
         builder: CustomDialogExample(),
       })
     }
  4. 点击与onClick事件绑定的组件使弹窗弹出。

    @Entry
    @Component
    struct CustomDialogUser {
      dialogController: CustomDialogController = new CustomDialogController({
        builder: CustomDialogExample(),
      })
    
      build() {
        Column() {
          Button('click me')
            .onClick(() => {
              this.dialogController.open()
            })
        }.width('100%').margin({ top: 5 })
      }
    }

弹窗的交互 点击→【纯血版鸿蒙全套最新学习资料】希望这一份鸿蒙学习资料能够给大家带来帮助

弹窗可用于数据交互,完成用户一系列响应操作。

  1. 在@CustomDialog装饰器内添加按钮,同时添加数据函数。

    @CustomDialog
    struct CustomDialogExample {
      cancel?: () => void
      confirm?: () => void
      controller: CustomDialogController
    
      build() {
        Column() {
          Text('我是内容').fontSize(20).margin({ top: 10, bottom: 10 })
          Flex({ justifyContent: FlexAlign.SpaceAround }) {
            Button('cancel')
              .onClick(() => {
                this.controller.close()
                if (this.cancel) {
                  this.cancel()
                }
              }).backgroundColor(0xffffff).fontColor(Color.Black)
            Button('confirm')
              .onClick(() => {
                this.controller.close()
                if (this.confirm) {
                  this.confirm()
                }
              }).backgroundColor(0xffffff).fontColor(Color.Red)
          }.margin({ bottom: 10 })
        }
      }
    }
  2. 页面内需要在构造器内进行接收,同时创建相应的函数操作。

    @Entry
    @Component
    struct CustomDialogUser {
      dialogController: CustomDialogController = new CustomDialogController({
        builder: CustomDialogExample({
          cancel: ()=> { this.onCancel() },
          confirm: ()=> { this.onAccept() },
        }),
      })
    
      onCancel() {
        console.info('Callback when the first button is clicked')
      }
    
      onAccept() {
        console.info('Callback when the second button is clicked')
      }
    
      build() {
        Column() {
          Button('click me')
            .onClick(() => {
              this.dialogController.open()
            })
        }.width('100%').margin({ top: 5 })
      }
    }

    3.可通过弹窗中的按钮实现路由跳转,同时获取跳转页面向当前页传入的参数。

    // Index.ets
    import { router } from '@kit.ArkUI';
    
    @CustomDialog
    struct CustomDialogExample {
      @Link textValue: string
      controller?: CustomDialogController
      cancel: () => void = () => {
      }
      confirm: () => void = () => {
      }
    
      build() {
        Column({ space: 20 }) {
          if (this.textValue != '') {
            Text(`第二个页面的内容为:${this.textValue}`)
              .fontSize(20)
          } else {
            Text('是否获取第二个页面的内容')
              .fontSize(20)
          }
          Flex({ justifyContent: FlexAlign.SpaceAround }) {
            Button('cancel')
              .onClick(() => {
                if (this.controller != undefined) {
                  this.controller.close()
                  this.cancel()
                }
              }).backgroundColor(0xffffff).fontColor(Color.Black)
            Button('confirm')
              .onClick(() => {
                if (this.controller != undefined && this.textValue != '') {
                  this.controller.close()
                } else if (this.controller != undefined) {
                  router.pushUrl({
                    url: 'pages/Index2'
                  })
                  this.controller.close()
                }
              }).backgroundColor(0xffffff).fontColor(Color.Red)
          }.margin({ bottom: 10 })
        }.borderRadius(10).padding({ top: 20 })
      }
    }
    
    @Entry
    @Component
    struct CustomDialogUser {
      @State textValue: string = ''
      dialogController: CustomDialogController | null = new CustomDialogController({
        builder: CustomDialogExample({
          cancel: () => {
            this.onCancel()
          },
          confirm: () => {
            this.onAccept()
          },
          textValue: $textValue
        })
      })
    
      // 在自定义组件即将析构销毁时将dialogController置空
      aboutToDisappear() {
        this.dialogController = null // 将dialogController置空
      }
    
      onPageShow() {
        const params = router.getParams() as Record<string, string>; // 获取传递过来的参数对象
        if (params) {
          this.dialogController?.open()
          this.textValue = params.info as string; // 获取info属性的值
        }
      }
    
      onCancel() {
        console.info('Callback when the first button is clicked')
      }
    
      onAccept() {
        console.info('Callback when the second button is clicked')
      }
    
      exitApp() {
        console.info('Click the callback in the blank area')
      }
    
      build() {
        Column() {
          Button('click me')
            .onClick(() => {
              if (this.dialogController != null) {
                this.dialogController.open()
              }
            }).backgroundColor(0x317aff)
        }.width('100%').margin({ top: 5 })
      }
    }
    // Index2.ets
    import { router } from '@kit.ArkUI';
    
    @Entry
    @Component
    struct Index2 {
      @State message: string = '点击返回';
      build() {
        Column() {
          Button(this.message)
            .fontSize(50)
            .fontWeight(FontWeight.Bold).onClick(() => {
            router.back({
              url: 'pages/Index',
              params: {
                info: 'Hello World'
              }
            });
          })
        }.width('100%').height('100%').margin({ top: 20 })
      }
    }

弹窗的动画 点击→【纯血版鸿蒙全套最新学习资料】希望这一份鸿蒙学习资料能够给大家带来帮助

弹窗通过定义openAnimation控制弹窗出现动画的持续时间,速度等参数。

@CustomDialog
struct CustomDialogExample {
  controller?: CustomDialogController

  build() {
    Column() {
      Text('Whether to change a text?').fontSize(16).margin({ bottom: 10 })
    }
  }
}

@Entry
@Component
struct CustomDialogUser {
  @State textValue: string = ''
  @State inputValue: string = 'click me'
  dialogController: CustomDialogController | null = new CustomDialogController({
    builder: CustomDialogExample(),
    openAnimation: {
      duration: 1200,
      curve: Curve.Friction,
      delay: 500,
      playMode: PlayMode.Alternate,
      onFinish: () => {
        console.info('play end')
      }
    },
    autoCancel: true,
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -20 },
    gridCount: 4,
    customStyle: false,
    backgroundColor: 0xd9ffffff,
    cornerRadius: 10,
  })

  // 在自定义组件即将析构销毁时将dialogController置空
  aboutToDisappear() {
    this.dialogController = null // 将dialogController置空
  }

  build() {
    Column() {
      Button(this.inputValue)
        .onClick(() => {
          if (this.dialogController != null) {
            this.dialogController.open()
          }
        }).backgroundColor(0x317aff)
    }.width('100%').margin({ top: 5 })
  }
}

弹窗的样式

弹窗通过定义宽度、高度、背景色、阴影等参数来控制样式。

@CustomDialog
struct CustomDialogExample {
  controller?: CustomDialogController

  build() {
    Column() {
      Text('我是内容').fontSize(16).margin({ bottom: 10 })
    }
  }
}

@Entry
@Component
struct CustomDialogUser {
  @State textValue: string = ''
  @State inputValue: string = 'click me'
  dialogController: CustomDialogController | null = new CustomDialogController({
    builder: CustomDialogExample(),
    autoCancel: true,
    alignment: DialogAlignment.Center,
    offset: { dx: 0, dy: -20 },
    gridCount: 4,
    customStyle: false,
    backgroundColor: 0xd9ffffff,
    cornerRadius: 20,
    width: '80%',
    height: '100px',
    borderWidth: 1,
    borderStyle: BorderStyle.Dashed,//使用borderStyle属性,需要和borderWidth属性一起使用
    borderColor: Color.Blue,//使用borderColor属性,需要和borderWidth属性一起使用
    shadow: ({ radius: 20, color: Color.Grey, offsetX: 50, offsetY: 0}),
  })

  // 在自定义组件即将析构销毁时将dialogController置空
  aboutToDisappear() {
    this.dialogController = null // 将dialogController置空
  }

  build() {
    Column() {
      Button(this.inputValue)
        .onClick(() => {
          if (this.dialogController != null) {
            this.dialogController.open()
          }
        }).backgroundColor(0x317aff)
    }.width('100%').margin({ top: 5 })
  }
}

嵌套自定义弹窗

通过第一个弹窗打开第二个弹窗时,最好将第二个弹窗定义在第一个弹窗的父组件处,通过父组件传给第一个弹窗的回调来打开第二个弹窗。

@CustomDialog
struct CustomDialogExampleTwo {
  controllerTwo?: CustomDialogController
  @State message: string = "I'm the second dialog box."
  @State showIf: boolean = false;
  build() {
    Column() {
      if (this.showIf) {
        Text("Text")
          .fontSize(30)
          .height(100)
      }
      Text(this.message)
        .fontSize(30)
        .height(100)
      Button("Create Text")
        .onClick(()=>{
          this.showIf = true;
        })
      Button ('Close Second Dialog Box')
        .onClick(() => {
          if (this.controllerTwo != undefined) {
            this.controllerTwo.close()
          }
        })
        .margin(20)
    }
  }
}
@CustomDialog
struct CustomDialogExample {
  openSecondBox?: ()=>void
  controller?: CustomDialogController

  build() {
    Column() {
      Button ('Open Second Dialog Box and close this box')
        .onClick(() => {
          this.controller!.close();
          this.openSecondBox!();
        })
        .margin(20)
    }.borderRadius(10)
  }
}
@Entry
@Component
struct CustomDialogUser {
  @State inputValue: string = 'Click Me'
  dialogController: CustomDialogController | null = new CustomDialogController({
    builder: CustomDialogExample({
      openSecondBox: ()=>{
        if (this.dialogControllerTwo != null) {
          this.dialogControllerTwo.open()
        }
      }
    }),
    cancel: this.exitApp,
    autoCancel: true,
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -20 },
    gridCount: 4,
    customStyle: false
  })
  dialogControllerTwo: CustomDialogController | null = new CustomDialogController({
    builder: CustomDialogExampleTwo(),
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -25 } })

  aboutToDisappear() {
    this.dialogController = null
    this.dialogControllerTwo = null
  }

  onCancel() {
    console.info('Callback when the first button is clicked')
  }

  onAccept() {
    console.info('Callback when the second button is clicked')
  }

  exitApp() {
    console.info('Click the callback in the blank area')
  }
  build() {
    Column() {
      Button(this.inputValue)
        .onClick(() => {
          if (this.dialogController != null) {
            this.dialogController.open()
          }
        }).backgroundColor(0x317aff)
    }.width('100%').margin({ top: 5 })
  }
}

由于自定义弹窗在状态管理侧有父子关系,如果将第二个弹窗定义在第一个弹窗内,那么当父组件(第一个弹窗)被销毁(关闭)时,子组件(第二个弹窗)内无法再继续创建新的组件。

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

Image通过调用接口来创建,接口调用形式如下: 点击→【纯血版鸿蒙全套最新学习资料】希望这一份鸿蒙学习资料能够给大家带来帮助

Image(src: PixelMap | ResourceStr | DrawableDescriptor)

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

加载图片资源

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

存档图类型数据源

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

  • 本地资源

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

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

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

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

    Image组件首次加载网络图片时,需要请求网络资源,非首次加载时,默认从缓存中直接读取图片

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

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

    图1 resources

    调用方式:

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

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

    图2 rawfile

    调用方式:

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

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

    1. 调用接口获取图库的照片url。
      import { picker } from '@kit.CoreFileKit';
      import { BusinessError } from '@kit.BasicServicesKit';
      
      @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%')
        }
      }
  1. 从媒体库获取的url格式通常如下。
    Image('file://media/Photos/5')
    .width(200)
  • base64

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

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

多媒体像素图

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

  1. 创建PixelMap状态变量。

    @State image: PixelMap | undefined = undefined;
  2. 引用多媒体。

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

    1. 引用网络权限与媒体库权限。
      import { http } from '@kit.NetworkKit';
      import { image } from '@kit.ImageKit';
      import { BusinessError } from '@kit.BasicServicesKit';
    2. 填写网络图片地址。
      let OutData: http.HttpResponse
      http.createHttp().request("https://www.example.com/xxx.png",
        (error: BusinessError, data: http.HttpResponse) => {
          if (error) {
            console.error(`http request failed with. Code: ${error.code}, message: ${error.message}`);
          } else {
            OutData = data
          }
        }
      )
    3. 将网络地址成功返回的数据,编码转码成pixelMap的图片格式。
      let code: http.ResponseCode | number = OutData.responseCode
      if (http.ResponseCode.OK === code) {
        let imageData: ArrayBuffer = OutData.result as ArrayBuffer;
        let imageSource: image.ImageSource = image.createImageSource(imageData);
      
        class tmp {
          height: number = 100
          width: number = 100
        }
      
        let si: tmp = new tmp()
        let options: Record<string, number | boolean | tmp> = {
          'alphaType': 0, // 透明度
          'editable': false, // 是否可编辑
          'pixelFormat': 3, // 像素格式
          'scaleMode': 1, // 缩略值
          'size': { height: 100, width: 100 }
        } // 创建图片大小
      
        class imagetmp {
          image: PixelMap | undefined = undefined
          set(val: PixelMap) {
            this.image = val
          }
        }
      
        imageSource.createPixelMap(options).then((pixelMap: PixelMap) => {
          let im = new imagetmp()
          im.set(pixelMap)
        })
      }
    4. 显示图片。
      class htp{
       httpRequest: Function | undefined = undefined
       set(){
         if(this.httpRequest){
           this.httpRequest()
         }
       }
      }
      Button("获取网络图片")
        .onClick(() => {
          let sethtp = new htp()
          sethtp.set()
        })
      Image(this.image).height(100).width(100)

显示矢量图

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

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

Image($r('app.media.cloud'))
  .width(50)
  .fillColor(Color.Blue) 

图3 原始图片

图4 设置绘制颜色后的svg图片

添加属性

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

设置图片缩放类型

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

@Entry
@Component
struct MyComponent {
  scroller: Scroller = new Scroller()

  build() {
    Scroll(this.scroller) {
      Column() {
        Row() {
          Image($r('app.media.img_2'))
            .width(200)
            .height(150)
            .border({ width: 1 })
              // 保持宽高比进行缩小或者放大,使得图片完全显示在显示边界内。
            .objectFit(ImageFit.Contain)
            .margin(15)
            .overlay('Contain', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.ic_img_2'))
            .width(200)
            .height(150)
            .border({ width: 1 })
            .objectFit(ImageFit.Cover)
            .margin(15)
              // 保持宽高比进行缩小或者放大,使得图片两边都大于或等于显示边界。
            .overlay('Cover', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.img_2'))
            .width(200)
            .height(150)
            .border({ width: 1 })
              // 自适应显示。
            .objectFit(ImageFit.Auto)
            .margin(15)
            .overlay('Auto', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        }

        Row() {
          Image($r('app.media.img_2'))
            .width(200)
            .height(150)
            .border({ width: 1 })
              // 不保持宽高比进行放大缩小,使得图片充满显示边界。
            .objectFit(ImageFit.Fill)
            .margin(15)
            .overlay('Fill', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.img_2'))
            .width(200)
            .height(150)
            .border({ width: 1 })
              // 保持宽高比显示,图片缩小或者保持不变。
            .objectFit(ImageFit.ScaleDown)
            .margin(15)
            .overlay('ScaleDown', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.img_2'))
            .width(200)
            .height(150)
            .border({ width: 1 })
              // 保持原有尺寸显示。
            .objectFit(ImageFit.None)
            .margin(15)
            .overlay('None', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        }
      }
    }
  }
}

图片插值

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

@Entry
@Component
struct Index {
  build() {
    Column() {
      Row() {
        Image($r('app.media.grass'))
          .width('40%')
          .interpolation(ImageInterpolation.None)
          .borderWidth(1)
          .overlay("Interpolation.None", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          .margin(10)
        Image($r('app.media.grass'))
          .width('40%')
          .interpolation(ImageInterpolation.Low)
          .borderWidth(1)
          .overlay("Interpolation.Low", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          .margin(10)
      }.width('100%')
      .justifyContent(FlexAlign.Center)

      Row() {
        Image($r('app.media.grass'))
          .width('40%')
          .interpolation(ImageInterpolation.Medium)
          .borderWidth(1)
          .overlay("Interpolation.Medium", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          .margin(10)
        Image($r('app.media.grass'))
          .width('40%')
          .interpolation(ImageInterpolation.High)
          .borderWidth(1)
          .overlay("Interpolation.High", { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          .margin(10)
      }.width('100%')
      .justifyContent(FlexAlign.Center)
    }
    .height('100%')
  }
}

设置图片重复样式

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

 点击→【纯血版鸿蒙全套最新学习资料】希望这一份鸿蒙学习资料能够给大家带来帮助

@Entry
@Component
struct MyComponent {
  build() {
    Column({ space: 10 }) {
      Row({ space: 5 }) {
        Image($r('app.media.ic_public_favor_filled_1'))
          .width(110)
          .height(115)
          .border({ width: 1 })
          .objectRepeat(ImageRepeat.XY)
          .objectFit(ImageFit.ScaleDown)
          // 在水平轴和竖直轴上同时重复绘制图片
          .overlay('ImageRepeat.XY', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.ic_public_favor_filled_1'))
          .width(110)
          .height(115)
          .border({ width: 1 })
          .objectRepeat(ImageRepeat.Y)
          .objectFit(ImageFit.ScaleDown)
          // 只在竖直轴上重复绘制图片
          .overlay('ImageRepeat.Y', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.ic_public_favor_filled_1'))
          .width(110)
          .height(115)
          .border({ width: 1 })
          .objectRepeat(ImageRepeat.X)
          .objectFit(ImageFit.ScaleDown)
          // 只在水平轴上重复绘制图片
          .overlay('ImageRepeat.X', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
    }.height(150).width('100%').padding(8)
  }
}

设置图片渲染模式

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

@Entry
@Component
struct MyComponent {
  build() {
    Column({ space: 10 }) {
      Row({ space: 50 }) {
        Image($r('app.media.example'))
          // 设置图片的渲染模式为原色 
          .renderMode(ImageRenderMode.Original)
          .width(100)
          .height(100)
          .border({ width: 1 })
            // overlay是通用属性,用于在组件上显示说明文字
          .overlay('Original', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
        Image($r('app.media.example'))
          // 设置图片的渲染模式为黑白
          .renderMode(ImageRenderMode.Template)
          .width(100)
          .height(100)
          .border({ width: 1 })
          .overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
      }
    }.height(150).width('100%').padding({ top: 20,right: 10 })
  }
}

设置图片解码尺寸

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

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

@Entry
@Component
struct Index {
  build() {
    Column() {
      Row({ space: 50 }) {
        Image($r('app.media.example'))
          .sourceSize({
            width: 40,
            height: 40
          })
          .objectFit(ImageFit.ScaleDown)
          .aspectRatio(1)
          .width('25%')
          .border({ width: 1 })
          .overlay('width:40 height:40', { align: Alignment.Bottom, offset: { x: 0, y: 40 } })
        Image($r('app.media.example'))
          .sourceSize({
            width: 90,
            height: 90
          })
          .objectFit(ImageFit.ScaleDown)
          .width('25%')
          .aspectRatio(1)
          .border({ width: 1 })
          .overlay('width:90 height:90', { align: Alignment.Bottom, offset: { x: 0, y: 40 } })
      }.height(150).width('100%').padding(20)
    }
  }
}

为图片添加滤镜效果

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

@Entry
@Component
struct Index {
  build() {
    Column() {
      Row() {
        Image($r('app.media.example'))
          .width('40%')
          .margin(10)
        Image($r('app.media.example'))
          .width('40%')
          .colorFilter(
            [1, 1, 0, 0, 0,
             0, 1, 0, 0, 0,
             0, 0, 1, 0, 0,
             0, 0, 0, 1, 0])
          .margin(10)
      }.width('100%')
      .justifyContent(FlexAlign.Center)
    }
  }
}

同步加载图片

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

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

事件调用

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

@Entry
@Component
struct MyComponent {
  @State widthValue: number = 0
  @State heightValue: number = 0
  @State componentWidth: number = 0
  @State componentHeight: number = 0

  build() {
    Column() {
      Row() {
        Image($r('app.media.ic_img_2'))
          .width(200)
          .height(150)
          .margin(15)
          .onComplete(msg => {
            if(msg){
              this.widthValue = msg.width
              this.heightValue = msg.height
              this.componentWidth = msg.componentWidth
              this.componentHeight = msg.componentHeight
            }
          })
            // 图片获取失败,打印结果
          .onError(() => {
            console.info('load image fail')
          })
          .overlay('\nwidth: ' + String(this.widthValue) + ', height: ' + String(this.heightValue) + '\ncomponentWidth: ' + String(this.componentWidth) + '\ncomponentHeight: ' + String(this.componentHeight), {
            align: Alignment.Bottom,
            offset: { x: 0, y: 60 }
          })
      }
    }
  }
}

  • 29
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值