可以通过新启一个duration为0的animateTo动画来打断原有动画效果,参考如下demo@Entry @Component struct Index { @State message: string = "Hello World"; @State opacityValue: number = 0.5 @State isRecording: boolean = false; build() { Row() { Column() { Text(this.message).fontSize(50).fontWeight(FontWeight.Bold).opacity(this.opacityValue).onClick(() => { if (this.isRecording) { // 设置一个duration为0的动画停掉上一次动画 animateTo({ duration: 0, iterations: 1, playMode: PlayMode.Normal }, () => { // 这里的opacityValue不可以和上一次设置的终止0.1 // 相同 this.opacityValue = 0.2 }) this.isRecording = false; // 再创建需要的动画 animateTo({ duration: 0, iterations: 1, playMode: PlayMode.Normal }, () => { this.opacityValue = 1 }) } else { this.isRecording = true animateTo({ duration: 1500, iterations: -1, }, () => { this.opacityValue = 0.1 }) } }) }.width("100%") }.height("100%") } }keyframeAnimateTo 方式,参考示例如下:import { UIContext } from '@kit.ArkUI'; @Entry @Component struct KeyframeDemo { @State myScale: number = 1.0; uiContext: UIContext | undefined = undefined; @State isRecording: boolean = false; aboutToAppear() { this.uiContext = this.getUIContext?.(); } build() { Column() { Circle() .width(100) .height(100) .fill("#46B1E3") .margin(100) .scale({ x: this.myScale, y: this.myScale }) .onClick(() => { if (!this.uiContext) { console.info("no uiContext, keyframe failed"); return; } this.myScale = 1; // 设置关键帧动画整体播放无限次 if(this.isRecording){ this.uiContext.keyframeAnimateTo({ iterations: -1 }, [ { // 关键帧动画时长为800ms,scale属性做从1到1.5的动画 duration: 800, event: () => { this.myScale = 1.5; } } ]) this.isRecording=false animateTo({ duration: 0, iterations: 1, playMode: PlayMode.Normal }, () => { this.myScale = 1 }) }else{ this.isRecording=true animateTo({ duration: 1500, iterations: -1, }, () => { this.myScale = 0.5; }) } }) }.width('100%').margin({ top: 5 }) } }
可以通过新启一个duration为0的animateTo动画来打断原有动画效果,参考如下demo
keyframeAnimateTo 方式,参考示例如下: