可以通过新启一个duration为0的animateTo动画来打断原有动画效果,参考如下demo
import { UIContext } from '[@kit](/user/kit).ArkUI';
[@Entry](/user/Entry)
[@Component](/user/Component)
struct KeyframeDemo {
[@State](/user/State) myScale: number = 1.0;
uiContext: UIContext | undefined = undefined;
[@State](/user/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 })
}
}