AutoImage.ets 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. // components/AutoImage.ets
  2. interface ImgSize {
  3. width: number
  4. height: number
  5. }
  6. @Component
  7. export struct AutoImage {
  8. @Prop src: PixelMap | ResourceStr | DrawableDescriptor
  9. @Prop fixedHeight: number = 120 // 固定高度(px)
  10. @State imgWidth: number = 0 // 按比例算出的宽度
  11. private naturalWidth: number = 0
  12. private naturalHeight: number = 0
  13. // 图片加载完成时,获取原图宽高并算宽度
  14. onImageLoad(info: ImgSize) {
  15. this.naturalWidth = info.width
  16. this.naturalHeight = info.height
  17. if (this.fixedHeight > 0 && this.naturalHeight > 0) {
  18. // 按比例计算宽度
  19. this.imgWidth = this.fixedHeight * (this.naturalWidth / this.naturalHeight)
  20. }
  21. }
  22. build() {
  23. Image(this.src)
  24. .width(this.imgWidth > 0 ? this.imgWidth : 0)// 动态计算宽度
  25. .height(this.fixedHeight)// 固定高度
  26. .objectFit(ImageFit.Fill)// 保持比例用Fill/Cover/Contain自行选择
  27. .onComplete((info) => {
  28. if (info) {
  29. this.onImageLoad({ width: info.width, height: info.height })
  30. }
  31. })
  32. }
  33. }