情绪分布图表:Stack 进度条 + 百分比计算

📅 2026/7/19 1:09:59
情绪分布图表:Stack 进度条 + 百分比计算
前言在“海风日记“的回顾页中情绪分布图表通过 Stack 进度条展示了不同情绪的比例让用户直观地了解自己的情绪趋势。本文将从ReviewTab.ets源码出发深入讲解进度条图表的实现。一、情绪数据模型interface MoodDataItem { label: string // 标签如 开心 count: number // 数量 color: string // 颜色 } private moodData: MoodDataItem[] [ { label: 开心, count: 8, color: COLOR_MOOD_SUNNY }, { label: 还不错, count: 5, color: COLOR_PRIMARY }, { label: 平静, count: 4, color: COLOR_MOOD_CALM }, { label: 低落, count: 2, color: COLOR_MOOD_LOW }, { label: 难过, count: 1, color: COLOR_MOOD_SAD }, ] private totalCount: number 20二、进度条实现ForEach(this.moodData, (item: MoodDataItem) { Row({ space: 10 }) { // 情绪标签 Text(item.label).fontSize(13).fontColor(COLOR_TEXT_MAIN).width(80) // 进度条 Stack({ alignContent: Alignment.Start }) { // 背景条 Row().height(8).width(100%) .backgroundColor(rgba(200,180,140,0.15)) .borderRadius(4) // 前景条 Row().height(8) .width(${(item.count / this.totalCount) * 100}%) .backgroundColor(item.color) .borderRadius(4) } .layoutWeight(1) // 数量 Text(${item.count}) .fontSize(12).fontColor(COLOR_TEXT_SECONDARY).width(24).textAlign(TextAlign.End) } .width(100%).alignItems(VerticalAlign.Center) }, (item: MoodDataItem) item.label)三、百分比计算// 宽度百分比 .width(${(item.count / this.totalCount) * 100}%)四、情绪颜色情绪颜色常量颜色开心COLOR_MOOD_SUNNY#F5A623还不错COLOR_PRIMARY#F5A623平静COLOR_MOOD_CALM#7ECAAE低落COLOR_MOOD_LOW#8BAFD6难过COLOR_MOOD_SAD#B0A8C8五、常见问题5.1 进度条宽度异常问题进度条宽度超过了 100%。原因百分比计算错误item.count / totalCount大于 1。解决方案确保totalCount是所有item.count的总和。总结本文通过“海风日记“的情绪分布图表深入讲解了进度条的实现Stack 叠加背景条 前景条百分比计算动态宽度情绪颜色每种情绪对应颜色数据模型MoodDataItem 接口下一篇文章将深入讲解时间维度切换敬请期待。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源Stack 容器文档Row 组件文档ForEach 文档海风日记项目源码[HarmonyOS 开发者官网](https://atomgit.com/openharmony/docs开源鸿蒙跨平台社区