一、功能简介
本篇将讲解如何在 HarmonyOS ArkTS 中为组件添加基本的动画效果,包括透明度、位移、缩放过渡,并在页面切换中加入自然的动效,提升用户体验。
二、页面结构
entry/src/main/ets/pages/AnimationDemo.ets
三、代码演示
@Entry
@Component
struct AnimationDemo {
@State visible: boolean = false
build() {
Column() {
Text('动画演示')
.fontSize(20)
.margin({ bottom: 16 })
Button(this.visible ? '隐藏方块' : '显示方块')
.onClick(() => {
this.visible = !this.visible
})
.margin({ bottom: 20 })
If(this.visible, () => {
// 加入淡入+位移动画
Column()
.width(120)
.height(120)
.backgroundColor('#007aff')
.borderRadius(12)
.animate({
opacity: { from: 0, to: 1, duration: 300 },
translate: { x: { from: -100, to: 0, duration: 300 } }
})
})
}
.width('100%')
.padding(20)
}
}
四、运行效果
初始页面:
[显示方块]
点击按钮后:
-
蓝色方块从左侧滑入并渐变出现;
-
再次点击按钮 → 方块立即消失。
你可以进一步在页面切换之间添加动画(使用自定义组件 + 路由封装过渡),或结合 onPageShow
触发入场动画。
五、常见易错点与解决方法
易错点 | 表现 | 原因 | 解决方法 |
---|---|---|---|
动画无效果 | 组件直接出现/消失 | 未调用 .animate() | 使用 .animate({}) 包裹目标样式变更 |
报错“animate 未定义” | 编译失败 | 写错组件层级 | .animate() 应紧跟在组件上 |
方块不显示 | 页面无反应 | 未在 If(...) 中加入动画组件 | 使用 If(this.visible, () => { Column().animate(...) }) |
只有透明度变化 | 位移动画无效 | translate 配置不对 | 使用嵌套结构 { x: { from, to, duration } } |
六、进阶建议
-
使用
.scale()
,.rotate()
,.timingCurve()
实现更自然动画; -
页面间切换可通过封装过渡动画组件实现;
-
可组合状态变量 + 动画实现弹窗、下拉、展开等效果。