对手势属性进行修改时,绑定手势gesture没有生效,如何解决该问题?
问题代码示例参考如下:
@Entry @Component struct PinchGesturePage { @State scaleValue: number = 1; private lastScale: number = 1; @State isGesture: boolean = false; build() { Stack() { Row() .width(200) .height(200) .margin({ top: 50 }) .backgroundColor('#61CFBE') .scale(this.isGesture ? { x: this.scaleValue, y: this.scaleValue, z: 1 } : null) .gesture(this.isGesture ? PinchGesture({ fingers: 2 }) .onActionStart(() => { // 在手势开始时,记录当前的缩放比例 this.lastScale = this.scaleValue; }) .onActionUpdate((event: GestureEvent | undefined) => { if (event) { // 计算新的缩放比例,将当前缩放比例乘以最后一次记录的缩放比例 let newScale = this.lastScale * event.scale; // 进行边界检查 if (newScale < 1) { newScale = 1; } else if (newScale > 5) { newScale = 5; } // 更新缩放值 this.scaleValue = newScale; } }) .onActionEnd(() => { // 手势结束时,不需要特殊处理 }) : null ); Row() .width(200) .height(200) .onClick(() => { this.isGesture = true; console.info(`TWT->onClick ${this.isGesture}`); }) .hitTestBehavior(HitTestMode.Transparent) .backgroundColor('#5291FF'); } .height('100%') .width('100%'); } }
使用手势拦截onGestureJudgeBegin来判断是否识别手势。
@Entry @Component struct PinchGesturePage { @State scaleValue: number = 1; private lastScale: number = 1; @State isGesture: boolean = false; build() { Stack() { Row() .width(400) .height(400) .margin({ top: 50 }) .backgroundColor('#61CFBE') .scale(this.isGesture ? { x: this.scaleValue, y: this.scaleValue, z: 1 } : null) .onGestureJudgeBegin(() => { if (this.isGesture) { return GestureJudgeResult.CONTINUE; } else { return GestureJudgeResult.REJECT; } }) .gesture(PinchGesture({ fingers: 2 }) .onActionStart(() => { // 在手势开始时,记录当前的缩放比例 console.info(`The lastScale is ${this.lastScale}`); this.lastScale = this.scaleValue; }) .onActionUpdate((event: GestureEvent | undefined) => { if (event) { // 计算新的缩放比例,将当前缩放比例乘以最后一次记录的缩放比例 let newScale = this.lastScale * event.scale; // 进行边界检查 if (newScale < 1) { newScale = 1; } else if (newScale > 5) { newScale = 5; } // 更新缩放值 this.scaleValue = newScale; console.info(`The newScale is ${this.scaleValue}`); } }) .onActionEnd(() => { // 手势结束时,不需要特殊处理 console.info('The action is end'); }) ); Row() .width(400) .height(400) .onClick(() => { this.isGesture = true; console.info(`TWT->onClick ${this.isGesture}`); }) .hitTestBehavior(HitTestMode.Transparent) .backgroundColor('#5291FF'); } .height('100%') .width('100%'); } }