37 行
1.1 KiB
Plaintext
37 行
1.1 KiB
Plaintext
|
|
// components/AutoImage.ets
|
|||
|
|
interface ImgSize {
|
|||
|
|
width: number
|
|||
|
|
height: number
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
@Component
|
|||
|
|
export struct AutoImage {
|
|||
|
|
@Prop src: PixelMap | ResourceStr | DrawableDescriptor
|
|||
|
|
@Prop fixedHeight: number = 120 // 固定高度(px)
|
|||
|
|
@State imgWidth: number = 0 // 按比例算出的宽度
|
|||
|
|
private naturalWidth: number = 0
|
|||
|
|
private naturalHeight: number = 0
|
|||
|
|
|
|||
|
|
// 图片加载完成时,获取原图宽高并算宽度
|
|||
|
|
onImageLoad(info: ImgSize) {
|
|||
|
|
this.naturalWidth = info.width
|
|||
|
|
this.naturalHeight = info.height
|
|||
|
|
if (this.fixedHeight > 0 && this.naturalHeight > 0) {
|
|||
|
|
// 按比例计算宽度
|
|||
|
|
this.imgWidth = this.fixedHeight * (this.naturalWidth / this.naturalHeight)
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
build() {
|
|||
|
|
Image(this.src)
|
|||
|
|
.width(this.imgWidth > 0 ? this.imgWidth : 0)// 动态计算宽度
|
|||
|
|
.height(this.fixedHeight)// 固定高度
|
|||
|
|
.objectFit(ImageFit.Fill)// 保持比例用Fill/Cover/Contain自行选择
|
|||
|
|
.onComplete((info) => {
|
|||
|
|
if (info) {
|
|||
|
|
this.onImageLoad({ width: info.width, height: info.height })
|
|||
|
|
}
|
|||
|
|
})
|
|||
|
|
}
|
|||
|
|
}
|