鸿蒙开发 ImageKnife二次封装
开源地址:
ImageKnife: 专门为OpenHarmony打造的一款图像加载缓存库,致力于更高效、更轻便、更简单
封装自定义组件:
import { ImageKnifeComponent } from '@ohos/imageknife';
/**
* 自定义图片加载
*/
@Component
export struct BaseImageView {
@State src: string | PixelMap | Resource = ""
@State placeSrc: string | PixelMap | Resource = ""
defaultPlaceSrc: string | PixelMap | Resource = $r("app.media.ic_place_default")
@State errorSrc: string | PixelMap | Resource = ""
@State mWidth: Length = ""
@State mHeight: Length = ""
@State radius: BorderRadiuses | Length | LocalizedBorderRadiuses = ""
@State fit: ImageFit = ImageFit.Fill
aboutToAppear(): void {
if (this.placeSrc) {
this.defaultPlaceSrc = this.placeSrc
}
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption: {
loadSrc: this.src,
placeholderSrc: this.defaultPlaceSrc,
placeholderObjectFit: ImageFit.Fill,
errorholderSrc: this.errorSrc,
objectFit: this.fit,
border: {
radius: this.radius
},
}
})
.width(this.mWidth)
.height(this.mHeight)
}
}
}
使用如下:
BaseImageView({
src: "https://img2.baidu.com/it/u=1237025922,2679733234&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1725382800&t=a1e37f873daad6046a78b63b2486c806",
mWidth: 200,
mHeight: 200,
})
3.0.1bug:
placeholderSrc传入会报错,导致图片显示不了
处理占位图方法
1:等待开源作者修复
2:在BaseImageView里使用stack+image(显示占位图),监听ImageKnifeComponent的onLoadListener的onLoadSuccess方法,控制image+ImageKnifeComponent显示和隐藏