@ohos.animator动画
支持自定义动画、手动开启动画、暂停、取消、重置、动画反向执行
- 定义
Animator类,依赖UI的执行上下文this.getUIContext().createAnimator()
| 功能 | 描述 |
|---|---|
| play | 开启动画执行,会从上一次的播放状态恢复执行 |
| pause | 暂停动画 |
| cancel | 取消动画 |
| reverse | 以相反的顺序播放动画 |
| finish | 结束动画 |
| reset | 更新当前动画器 |
import { AnimatorResult, LengthUnit } from "@kit.ArkUI";
import { hilog } from "@kit.PerformanceAnalysisKit";
@ComponentV2
export struct AnimatorComponent {
private _animation: AnimatorResult | undefined;
@Local _w: number = 0;
@Local _h: number = 0;
// 定义动画
createAnimation() {
// https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V13/js-apis-animator-V13#animatoroptions
this._animation = this.getUIContext().createAnimator({
// 动画播放的时长 ms
duration: 2000,
// 动画插值曲线
easing: 'linear',
// 延时动画 ms
delay: 0,
// 动画执行后是否恢复到初始状态
fill: 'forwards',
// 动画播放模式
direction: 'alternate',
// 动画播放次数 -1为无限次
iterations: 1,
// 动画插值起点 默认0
begin: 0,
// 动画插值终点 默认1
end: 100
});
// 动画完成时回调
this._animation.onFinish = () => {
hilog.info(0x0123, '', '监听到动画执行完成')
}
// 动画被取消时回调
this._animation.onCancel = () => {
hilog.info(0x0123, '', '监听到动画被取消')
}
// 动画重复时回调
this._animation.onRepeat = () => {
hilog.info(0x0123, '', '监听到动画重复执行')
}
// 接收到帧时回调
this._animation.onFrame = (progress: number) => {
hilog.info(0x0123, '', '接收到帧回调 => ' + progress)
this._w = progress;
this._h = progress;
}
}
aboutToAppear(): void {
this.createAnimation()
}
build() {
NavDestination() {
Row().width(this._w).height(this._h).backgroundColor(Color.Orange)
Flex({
wrap: FlexWrap.Wrap,
space: {
main: { value: 10, unit: LengthUnit.VP },
cross: { value: 10, unit: LengthUnit.VP }
}
}) {
Button('启动动画').fontSize(10)
.onClick(() => {
// 启动动画,动画会保留上一次的播放状态
this._animation?.play()
})
Button('暂停动画').fontSize(10)
.onClick(() => {
// 暂停动画
this._animation?.pause()
})
Button('结束动画').fontSize(10)
.onClick(() => {
// 结束动画
this._animation?.finish()
})
Button('取消动画').fontSize(10)
.onClick(() => {
// 取消动画
this._animation?.cancel()
})
Button('以相反的顺序播放动画').fontSize(10)
.onClick(() => {
// 以相反的顺序播放动画
this._animation?.reverse()
})
Button('更新动画')
.onClick(() => {
this._animation?.reset({
// 动画播放的时长 ms
duration: 500,
easing: 'linear',
delay: 0,
fill: 'forwards',
direction: 'alternate',
iterations: 10,
begin: 0,
end: 100
})
})
}
.margin({ top: 10 })
}
.width('100%')
.height('100%')
}
}