鸿蒙Next 可暂停的属性动画

180 阅读1分钟

做音乐播放器时,播放状态有一个无限旋转的动效,音乐暂停时需要同步暂停,属性动画animation使用起来有一点问题,偶然发现了另一个Api,同样可以实现属性动画的效果,特此记录。
相关代码:
个人仓库链接

import { AnimatorOptions, AnimatorResult } from '@kit.ArkUI'

@Component
export struct RotateAnimator {
  //旋转角度
  @State angle: number = 0
  //定义Animator结果接口。
  private rotateAnimator: AnimatorResult | undefined = undefined
  //定义动画选项。
  private options: AnimatorOptions = {
    //动画播放的时长
    duration: 1000,
    //动画插值曲线
    easing: "linear",
    //动画延时播放时长,单位毫秒,设置为0时,表示不延时
    delay: 0,
    //动画执行后是否恢复到初始状态
    fill: "none",
    //动画播放模式。
    direction: "normal",
    //动画播放次数。设置为0时不播放,设置为-1时无限次播放
    iterations: -1,
    //动画插值起点。默认值:0。
    begin: 0,
    //动画插值终点。默认值:1
    end: 360
  };

  build() {
    Column({ space: 20 }) {
      Image($r("app.media.app_icon")).size({ width: 200, height: 200 })
        .rotate({ angle: this.angle })
      Row() {
        Button('旋转').onClick(() => {
          this.rotateAnimator?.play()
        })

        Button('暂停').onClick(() => {
          this.rotateAnimator?.pause()
        })
      }.justifyContent(FlexAlign.SpaceAround).width('100%')
    }.alignItems(HorizontalAlign.Center).width('100%')
  }

  aboutToAppear(): void {
    this.create()
  }

  create() {
    this.rotateAnimator = this.getUIContext().createAnimator(this.options)

    this.rotateAnimator.onFinish = () => {
      console.info("动画结束")
    }
    this.rotateAnimator.onRepeat = () => {
      console.info("动画重复")
    }
    this.rotateAnimator.onCancel = () => {
      console.info("动画取消")
    }
    this.rotateAnimator.onFrame = (value: number) => {
      this.angle = value
    }
  }
}

参考:
@ohos.animator (动画)