3. 图片组件构建
在 ImageComponent 组件中,构建图片展示部分,设置图片的宽度、高度、缩放和偏移等属性,并监听图片加载完成事件。
build() {
Column() {
Image(`${CommonUrl.CLOUD_STORAGE_URL}${this.image}`)
.onComplete((e) => {
this.imageWidth = (e?.width || 0)
this.imageHeight = (e?.height || 0)
})
.objectFit(ImageFit.Cover)
.width(this.imageWidth + 'px')
.height(this.imageHeight + 'px')
.scale({
x: this.geometryScale,
y: this.geometryScale
})
.offset({
x: this.geometryOffsetX,
y: this.geometryOffsetY
})
.focusable(true)
.objectFit(ImageFit.Cover)
.autoResize(false)
.sharedTransition('sharedImage', {
duration: 200,
curve: Curve.Linear,
})
}
// ... 其他代码 ...
}
4. 图片缩放功能
通过 PinchGesture 绑定二指捏合手势,在手势更新时计算缩放比例,实现图片的缩放效果。当缩放比例小于 1 时,调用 reset 方法将图片恢复到初始状态。
parallelGesture(
GestureGroup(GestureMode.Exclusive,
PinchGesture({ fingers: 2 })
.onActionStart((event: GestureEvent) => {
})
.onActionUpdate((event: GestureEvent) => {
const s = this.preGeometryScale * event.scale;
this.geometryScale = Math.max(0.6, Math.min(2, s))
})
.onActionEnd(async () => {
this.preGeometryScale = this.geometryScale
if (this.preGeometryScale < 1) {
await this.reset()
}
}),
// ... 其他代码 ...
)
)
reset(): Promise<void> {
return new Promise((resolve, reject) => {
this.preGeometryScale = 1
if (this.geometryScale === 1) {
reject()
}
animateTo({ duration: 200, onFinish: resolve }, () => {
this.geometryScale = 1
this.geometryOffsetX = 0
this.geometryOffsetY = 0
})
})
}
通过以上核心功能的实现,在HarmonyOS 5应用中成功开发了图片预览页面,为用户提供了便捷的图片预览和操作体验。