#跟着晓明学鸿蒙# HarmonyOS Stack组件实现对话框动画效果
·
案例介绍
本教程将介绍如何为自定义对话框添加动画效果。我们将实现对话框显示和隐藏时的过渡动画,包括缩放、平移和透明度变化,以提升用户体验。
代码实现
@Entry
@Component
struct CustomDialogExample {
@Builder
InfoDialog() {
Column()
.width('100%')
.height('100%')
.backgroundColor('#00000080')
Column() {
Text('信息提示')
.fontSize(20)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 16 })
Text('这是一个信息提示对话框,用于向用户展示重要信息。')
.fontSize(16)
.margin({ bottom: 24 })
.textAlign(TextAlign.Center)
Button('确定')
.width('100%')
.height(40)
}
.width('80%')
.padding(24)
.backgroundColor(Color.White)
.borderRadius(16)
.shadow({
radius: 24,
color: '#00000040',
offsetX: 0,
offsetY: 4
})
// 缩放和淡入动画
.scale({ x: 0.8, y: 0.8 })
.opacity(0)
.animation({
delay: 0,
duration: 200,
curve: Curve.EaseOut,
playMode: PlayMode.Normal
})
.scale({ x: 1, y: 1 })
.opacity(1)
}
@Builder
ConfirmDialog() {
Column()
.width('100%')
.height('100%')
.backgroundColor('#00000080')
Column() {
// 对话框内容...
}
.width('80%')
.padding(24)
.backgroundColor(Color.White)
.borderRadius(16)
.shadow({
radius: 24,
color: '#00000040',
offsetX: 0,
offsetY: 4
})
// 上移和淡入动画
.translate({ y: 50 })
.opacity(0)
.animation({
delay: 0,
duration: 200,
curve: Curve.EaseOut
})
.translate({ y: 0 })
.opacity(1)
}
@Builder
InputDialog() {
Column()
.width('100%')
.height('100%')
.backgroundColor('#00000080')
Column() {
// 对话框内容...
}
.width('80%')
.padding(24)
.backgroundColor(Color.White)
.borderRadius(16)
.shadow({
radius: 24,
color: '#00000040',
offsetX: 0,
offsetY: 4
})
// 放大和淡入动画
.scale({ x: 1.2, y: 1.2 })
.opacity(0)
.animation({
delay: 0,
duration: 200,
curve: Curve.EaseOut
})
.scale({ x: 1, y: 1 })
.opacity(1)
}
}
代码详解
动画属性设置
-
基础样式
- 宽度设置为80%,居中显示
- 白色背景和圆角边框
- 添加阴影效果增强层次感
-
动画类型
- 信息对话框:缩放+淡入
- 确认对话框:上移+淡入
- 输入对话框:放大+淡入
-
动画参数
- duration: 200ms动画持续时间
- curve: EaseOut缓动曲线
- delay: 0无延迟立即开始
- playMode: Normal正常播放模式
动画实现细节
-
缩放动画
.scale({ x: 0.8, y: 0.8 }) .animation({ duration: 200, curve: Curve.EaseOut }) .scale({ x: 1, y: 1 })
- 初始缩小到0.8倍
- 动画过渡到原始大小
- 使用EaseOut曲线使动画更自然
-
平移动画
.translate({ y: 50 }) .animation({ duration: 200, curve: Curve.EaseOut }) .translate({ y: 0 })
- 初始向下偏移50单位
- 动画过渡到原始位置
- 配合透明度变化效果更好
-
透明度动画
.opacity(0) .animation({ duration: 200, curve: Curve.EaseOut }) .opacity(1)
- 初始完全透明
- 动画过渡到完全不透明
- 与其他动画同步进行
视觉效果增强
-
阴影效果
.shadow({ radius: 24, color: '#00000040', offsetX: 0, offsetY: 4 })
- 适当的阴影半径
- 半透明的阴影颜色
- 向下的阴影偏移
-
圆角和内边距
- borderRadius设置为16
- padding设置为24
- 提供舒适的视觉效果
总结
通过合理使用动画属性和过渡效果,我们为对话框添加了流畅的显示动画。不同类型的对话框使用不同的动画效果,既保持了视觉的统一性,又增加了界面的趣味性。配合阴影和圆角等视觉效果,创造出专业和现代的对话框体验。
更多推荐
所有评论(0)