鸿蒙NEXT实现点赞动态效果
图片展示效果
【开发环境准备】
电脑系统:windows 10
开发工具:DevEco Studio NEXT Beta1 Build Version: 5.0.3.806
工程版本:API 12
真机:Mate 60 Pro
语言:ArkTS、ArkUI
观察者模式:
描述:观察者模式是一种行为设计模式,其中一个对象(称为主题)维护一系列依赖于它的对象(称为观察者),当主题的状态发生变化时,它会通知所有观察者并自动更新。
代码片段:在代码中,通过 @ObservedV2 装饰器将 Cell 类标记为观察者,使用 @Trace 装饰器跟踪属性变化。
动画效果:
描述:动画效果用于为用户界面元素添加交互性和视觉吸引力。在代码中,通过动画效果使文字在点击图片时产生垂直移动和透明度变化的效果。
代码片段:在 onClick 回调中,使用 animateToImmediately 方法实现了文字的垂直移动和透明度变化的动画效果。
完整代码
// 观察者模式装饰器
@ObservedV2
class Cell {
value: string = '功德+1'; // 默认显示的文字
@Trace
rotateValue: number = 0; // 文字的垂直偏移量
@Trace // 跟踪属性变化
opacityValue: number = 0; // 文字透明度
@Trace // 跟踪属性变化
translateY: number = 0; // 文字的垂直偏移量
@Trace
fontSize:number = 10
}
// 主入口组件
@Entry
@Component
struct Index {
@State list: Cell[] = []; // 存储所有 Cell 对象的数组
indexCount: number = 0; // 记录当前滚动的索引
count: number = 10; // 列表中 Cell 对象的数量
// 初始化方法,在组件即将显示时被调用
aboutToAppear(): void {
for (let i = 0; i < this.count; i++) {
this.list.push(new Cell()); // 初始化 Cell 数组
}
}
// 构建 UI 的方法
build() {
Column() { // 创建一个垂直布局容器
Stack() { // 创建一个堆栈布局容器
ForEach(this.list, (item: Cell, _index: number) => { // 遍历 list 中的每一个 Cell
Text(item.value)// 显示 Cell 中的文字
.fontColor(Color.Black)// 设置文字颜色为白色
.fontSize(item.fontSize)// 设置文字大小
.rotate({angle:item.rotateValue})
.translate({ x: 0, y: item.translateY })// 设置文字的垂直偏移量
.opacity(item.opacityValue) // 设置文字的透明度
})
}
.width(300) // 设置堆栈布局容器的宽度
.height(300) // 设置堆栈布局容器的高度
.align(Alignment.Bottom) // 设置对齐方式为底部右端
Button('点赞')// 显示图片
.clickEffect({
// 点击效果配置
scale: 0.5, // 缩放比例
level: ClickEffectLevel.LIGHT // 效果级别
})
.onClick(() => { // 点击图片时触发的回调
let index = this.indexCount % this.count; // 计算当前滚动的索引
this.indexCount++; // 更新索引计数器
animateToImmediately({
// 立即开始动画
duration: 0, // 动画持续时间为0毫秒
onFinish: () => { // 动画完成后的回调
animateToImmediately({
// 再次立即开始动画
duration: 1000, // 动画持续时间为1000毫秒
}, () => {
this.list[index].translateY = -100 // 设置 Cell 的垂直偏移量
this.list[index].opacityValue = 0 // 设置 Cell 的透明度
this.list[index].fontSize = 20// 设置 Cell 的透明度
this.list[index].rotateValue = (index%2==0?60:-60 ) // 设置 Cell 的透明度
})
}
}, () => {
this.list[index].translateY = 0 // 设置 Cell 的垂直偏移量
this.list[index].opacityValue = 1 // 设置 Cell 的透明度
this.list[index].rotateValue = 0 // 设置 Cell 的透明度
this.list[index].fontSize = 10 // 设置 Cell 的透明度
})
})
}
.height('100%') // 设置容器高度为100%
.width('100%') // 设置容器宽度为100%
}
}