想要实现期望效果,单一手势无法完成,需要使用到GestureGroup组合手势并将组合模式设置为GestureMode.Parallel(并发执行手势)。
实现步骤如下:
LongPressGesture({ repeat: true })
.onAction((event: GestureEvent) => {
if (event && event.repeat) {
this.getUIContext()?.animateTo({ curve: curves.springMotion() }, () => {
this.picSize = 150;
});
this.isActive = true;
};
})
.onActionEnd(() => {
this.getUIContext()?.animateTo({ curve: curves.springMotion() }, () => {
this.picSize = 100;
});
this.isActive = false;
}), PanGesture()
.onActionUpdate((e) => {
this.offsetX = this.isActive ? e.offsetX : 0;
this.offsetY = this.isActive ? e.offsetY : 0;
})
.onActionEnd(() => {
this.positionX += this.offsetX;
this.positionY += this.offsetY;
this.offsetX = 0;
this.offsetY = 0;
}) 完整示例参考如下:
import { curves, display } from '@kit.ArkUI';
@Entry
@Component
struct DragDemo {
screenWidth: number = this.getUIContext().px2vp(display.getDefaultDisplaySync().width);
screenHeight: number = this.getUIContext().px2vp(display.getDefaultDisplaySync().height);
@State offsetX: number = 0;
@State offsetY: number = 0;
@State positionX: number = (this.screenWidth - 100) / 2; // 设置居中
@State positionY: number = (this.screenHeight - 100) / 2 - 50; // 设置居中
@State picSize: number = 100;
@State isActive: boolean = false;
build() {
RelativeContainer() {
Column() {
// 示例图片,请根据需求选择图片
Image($r('app.media.startIcon'))
.draggable(false)
.width(this.picSize)
.height(this.picSize)
.translate({ x: this.positionX + this.offsetX, y: this.positionY + this.offsetY, z: 0 })
.gesture(
GestureGroup(GestureMode.Parallel,
// 添加长按事件,长按后触发图片动效放大,松手后图片动效缩小
LongPressGesture({ repeat: true })
.onAction((event: GestureEvent) => {
if (event && event.repeat) {
this.getUIContext()?.animateTo({ curve: curves.springMotion() }, () => {
this.picSize = 150;
});
this.isActive = true;
};
})
.onActionEnd(() => {
this.getUIContext()?.animateTo({ curve: curves.springMotion() }, () => {
this.picSize = 100;
});
this.isActive = false;
}),
// 在长按事件触发后执行拖动事件,根据拖动对图片进行位移
PanGesture()
.onActionUpdate((e) => {
this.offsetX = this.isActive ? e.offsetX : 0;
this.offsetY = this.isActive ? e.offsetY : 0;
})
.onActionEnd(() => {
this.positionX += this.offsetX;
this.positionY += this.offsetY;
this.offsetX = 0;
this.offsetY = 0;
})
)
);
}
}
}
} 实现效果:
