完整代码如下所示:
@Entry
@Component
struct TransitionEffectPage {
// 组件往右的偏移量
@State offsetX: number = 0;
@State opacityNum: number = 0;
build() {
Column() {
Row() {
Column() {
}
.justifyContent(FlexAlign.Center)
.backgroundColor(Color.White)
.width('100%')
.height(200);
Row() {
// 图片资源仅作展示,根据实际替换
Image($r('app.media.vip_sn_star'))
.width(200)
.height(200)
.opacity(this.opacityNum);
}
.margin({ top: 24 });
}
.offset({ x: this.offsetX })
.gesture(
// 平移手势,滑动最小距离为5vp时识别成功。
PanGesture({ direction: PanDirection.Horizontal, distance: 1 })
// Pan手势移动过程中回调
.onActionUpdate((event: GestureEvent) => {
if (event.offsetX < 0) {
this.offsetX = event.offsetX;
} else {
this.offsetX = -290 + event.offsetX;
}
})
.onActionEnd(() => {
// 控制组件滑出屏幕外
if (this.offsetX > -60) {
this.getUIContext()?.animateTo({
duration: 300,
}, () => {
this.opacityNum = 0;
this.offsetX = 0;
});
}
// 控制组件滑动到中央
else {
this.getUIContext()?.animateTo({
duration: 300,
}, () => {
this.opacityNum = 1;
this.offsetX = -290;
});
}
})
);
}
.width('100%')
.height('100%');
}
} 效果图:
