#鸿蒙通关秘籍#如何实现鸿蒙应用中的左右拖动切换图片效果?

HarmonyOS
5天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
时光笔ETL

实现鸿蒙应用中的左右拖动切换图片效果,首先需要在布局中创建两个 Stack 组件,用于展示前后对比图。在两个 Stack 之间插入一个 Column 组件用于放置操作按钮。通过手势监听来调整组件的显示区域,具体实现如下:

ts Row() { Stack() {...} .zIndex(1) .width(this.leftImageWidth) .clip(true) .alignContent(Alignment.TopStart)

Column() {...} .width($r('app.integer.dragtoswitchpictures_drag_button_stack_width')) .zIndex(2)

Stack() {...} .zIndex(1) .clip(true) .width(this.rightImageWidth) .alignContent(Alignment.TopEnd) } .justifyContent(FlexAlign.Center) .width($r('app.string.dragtoswitchpictures_full_size'))

然后,使用 PanGesture 监听左右拖动操作,以实时调整左右侧图片的宽度。

ts Image($r('app.media.dragtoswitchpictures_drag_button')) .gesture( PanGesture({ fingers: 1, distance: 1 }) .onActionStart(() => { this.dragRefOffset = 0; }) .onActionUpdate((event) => { this.dragRefOffset = event.offsetX; this.leftImageWidth = this.imageWidth + this.dragRefOffset; this.rightImageWidth = 340 - this.leftImageWidth; if (this.leftImageWidth >= 310) { this.leftImageWidth = 310; this.rightImageWidth = 30; } else if (this.leftImageWidth <= 30) { this.leftImageWidth = 30; this.rightImageWidth = 310; } }) .onActionEnd(() => { if (this.leftImageWidth <= 30) { this.leftImageWidth = 30; this.rightImageWidth = 310; this.imageWidth = 30; } else if (this.leftImageWidth >= 310) { this.leftImageWidth = 310; this.rightImageWidth = 30; this.imageWidth = 310; } else { this.leftImageWidth = this.imageWidth + this.dragRefOffset; this.rightImageWidth = 340 - this.leftImageWidth; this.imageWidth = this.leftImageWidth; } }) )

分享
微博
QQ
微信
回复
5天前
相关问题