查看: 83|回复: 0

鸿蒙特效教程07-九宫格幸运抽奖

[复制链接]

1

主题

0

回帖

13

积分

新手上路

积分
13
发表于 2025-4-1 08:45:31 | 显示全部楼层 |阅读模式
鸿蒙特效教程07-九宫格幸运抽奖

在移动应用中,抽奖功能是一种常见且受欢迎的交互方式,能够有效提升用户粘性。本教程将带领大家从零开始,逐步实现一个九宫格抽奖效果,适合HarmonyOS开发的初学者阅读。
最终效果预览

我们将实现一个经典的九宫格抽奖界面,包含以下核心功能:
    3×3网格布局展示奖品点击中间按钮启动抽奖高亮格子循环移动的动画效果动态变速,模拟真实抽奖过程预设中奖结果的展示

实现步骤

步骤一:创建基本结构和数据模型

首先,我们需要创建一个基础页面结构和定义数据模型。通过定义奖品的数据结构,为后续的九宫格布局做准备。
  1. // 定义奖品项的接口
  2. interface PrizeItem {
  3.   id: number
  4.   name: string
  5.   icon: ResourceStr
  6.   color: string
  7. }
  8. @Entry
  9. @Component
  10. struct LuckyDraw {
  11.   // 基本页面结构
  12.   build() {
  13.     Column() {
  14.       Text('幸运抽奖')
  15.         .fontSize(24)
  16.         .fontColor(Color.White)
  17.     }
  18.     .width('100%')
  19.     .height('100%')
  20.     .backgroundColor('#121212')
  21.   }
  22. }
复制代码
在这一步,我们定义了 PrizeItem接口来规范奖品的数据结构,并创建了一个基本的页面结构,只包含一个标题。
步骤二:创建奖品数据和状态管理

接下来,我们添加具体的奖品数据,并定义抽奖功能所需的状态变量。
  1. @Entry
  2. @Component
  3. struct LuckyDraw {
  4.   // 定义奖品数组
  5.   @State prizes: PrizeItem[] = [
  6.     { id: 1, name: '谢谢参与', icon: $r('app.media.startIcon'), color: '#FF9500' },
  7.     { id: 2, name: '10积分', icon: $r('app.media.startIcon'), color: '#34C759' },
  8.     { id: 3, name: '优惠券', icon: $r('app.media.startIcon'), color: '#007AFF' },
  9.     { id: 8, name: '1元红包', icon: $r('app.media.startIcon'), color: '#FF3B30' },
  10.     { id: 0, name: '开始\n抽奖', icon: $r('app.media.startIcon'), color: '#FF2D55' },
  11.     { id: 4, name: '5元红包', icon: $r('app.media.startIcon'), color: '#5856D6' },
  12.     { id: 7, name: '免单券', icon: $r('app.media.startIcon'), color: '#E73C39' },
  13.     { id: 6, name: '50积分', icon: $r('app.media.startIcon'), color: '#38B0DE' },
  14.     { id: 5, name: '会员卡', icon: $r('app.media.startIcon'), color: '#39A5DC' },
  15.   ]
  16.   // 当前高亮的奖品索引
  17.   @State currentIndex: number = -1
  18.   // 是否正在抽奖
  19.   @State isRunning: boolean = false
  20.   // 中奖结果
  21.   @State result: string = '点击开始抽奖'
  22.   build() {
  23.     // 页面结构保持不变
  24.   }
  25. }
复制代码
在这一步,我们添加了以下内容:
    创建了一个包含9个奖品的数组,每个奖品都有id、名称、图标和颜色属性添加了三个状态变量:
      currentIndex:跟踪当前高亮的奖品索引isRunning:标记抽奖是否正在进行result:记录并显示抽奖结果

步骤三:实现九宫格布局

现在我们来实现九宫格的基本布局,使用Grid组件和ForEach循环遍历奖品数组。
  1. build() {
  2.   Column({ space: 30 }) {
  3.     // 标题
  4.     Text('幸运抽奖')
  5.       .fontSize(24)
  6.       .fontWeight(FontWeight.Bold)
  7.       .fontColor(Color.White)
  8.     // 结果显示区域
  9.     Column() {
  10.       Text(this.result)
  11.         .fontSize(20)
  12.         .fontColor(Color.White)
  13.     }
  14.     .width('90%')
  15.     .padding(15)
  16.     .backgroundColor('#0DFFFFFF')
  17.     .borderRadius(16)
  18.     // 九宫格抽奖区域
  19.     Grid() {
  20.       ForEach(this.prizes, (prize: PrizeItem, index) => {
  21.         GridItem() {
  22.           Column() {
  23.             if (index === 4) {
  24.               // 中间的开始按钮
  25.               Button({ type: ButtonType.Capsule }) {
  26.                 Text(prize.name)
  27.                   .fontSize(18)
  28.                   .fontWeight(FontWeight.Bold)
  29.                   .textAlign(TextAlign.Center)
  30.                   .fontColor(Color.White)
  31.               }
  32.               .width('90%')
  33.               .height('90%')
  34.               .backgroundColor(prize.color)
  35.             } else {
  36.               // 普通奖品格子
  37.               Image(prize.icon)
  38.                 .width(40)
  39.                 .height(40)
  40.               Text(prize.name)
  41.                 .fontSize(14)
  42.                 .fontColor(Color.White)
  43.                 .margin({ top: 8 })
  44.                 .textAlign(TextAlign.Center)
  45.             }
  46.           }
  47.           .width('100%')
  48.           .height('100%')
  49.           .justifyContent(FlexAlign.Center)
  50.           .alignItems(HorizontalAlign.Center)
  51.           .backgroundColor(prize.color)
  52.           .borderRadius(12)
  53.           .padding(10)
  54.         }
  55.       })
  56.     }
  57.     .columnsTemplate('1fr 1fr 1fr')
  58.     .rowsTemplate('1fr 1fr 1fr')
  59.     .columnsGap(10)
  60.     .rowsGap(10)
  61.     .width('90%')
  62.     .aspectRatio(1)
  63.     .backgroundColor('#0DFFFFFF')
  64.     .borderRadius(16)
  65.     .padding(10)
  66.   }
  67.   .width('100%')
  68.   .height('100%')
  69.   .justifyContent(FlexAlign.Center)
  70.   .backgroundColor(Color.Black)
  71.   .linearGradient({
  72.     angle: 135,
  73.     colors: [
  74.       ['#121212', 0],
  75.       ['#242424', 1]
  76.     ]
  77.   })
  78. }
复制代码
在这一步,我们实现了以下内容:
    创建了整体的页面布局,包括标题、结果显示区域和九宫格区域使用 Grid 组件创建3×3的网格布局使用 ForEach 遍历奖品数组,为每个奖品创建一个格子根据索引判断,为中间位置创建"开始抽奖"按钮,其他位置显示奖品信息为每个格子设置了合适的样式和背景色
步骤四:实现高亮效果和点击事件

接下来,我们要实现格子的高亮效果,并添加点击事件处理。
  1. build() {
  2.   Column({ space: 30 }) {
  3.     // 前面的代码保持不变...
  4.     // 九宫格抽奖区域
  5.     Grid() {
  6.       ForEach(this.prizes, (prize: PrizeItem, index) => {
  7.         GridItem() {
  8.           Column() {
  9.             if (index === 4) {
  10.               // 中间的开始按钮
  11.               Button({ type: ButtonType.Capsule }) {
  12.                 Text(prize.name)
  13.                   .fontSize(18)
  14.                   .fontWeight(FontWeight.Bold)
  15.                   .textAlign(TextAlign.Center)
  16.                   .fontColor(Color.White)
  17.               }
  18.               .width('90%')
  19.               .height('90%')
  20.               .backgroundColor(prize.color)
  21.               .onClick(() => this.startLottery()) // 添加点击事件
  22.             } else {
  23.               // 普通奖品格子
  24.               Image(prize.icon)
  25.                 .width(40)
  26.                 .height(40)
  27.               Text(prize.name)
  28.                 .fontSize(14)
  29.                 .fontColor(index === this.currentIndex ? prize.color : Color.White) // 高亮时修改文字颜色
  30.                 .margin({ top: 8 })
  31.                 .textAlign(TextAlign.Center)
  32.             }
  33.           }
  34.           .width('100%')
  35.           .height('100%')
  36.           .justifyContent(FlexAlign.Center)
  37.           .alignItems(HorizontalAlign.Center)
  38.           .backgroundColor(index === this.currentIndex && index !== 4 ? Color.White : prize.color) // 高亮时切换背景色
  39.           .borderRadius(12)
  40.           .padding(10)
  41.           .animation({ // 添加动画效果
  42.             duration: 200,
  43.             curve: Curve.EaseInOut
  44.           })
  45.         }
  46.       })
  47.     }
  48.     // Grid的其他属性保持不变...
  49.   }
  50.   // Column的属性保持不变...
  51. }
  52. // 添加开始抽奖的空方法
  53. startLottery() {
  54.   // 在下一步实现
  55. }
复制代码
在这一步,我们:
    为中间的"开始抽奖"按钮添加了点击事件处理方法 startLottery()实现了格子高亮效果:
      当格子被选中时(index === this.currentIndex),背景色变为白色,文字颜色变为奖品颜色添加了动画效果,使高亮切换更加平滑
    预定义了 startLottery()方法,暂时为空实现
步骤五:实现抽奖动画逻辑

现在我们来实现抽奖动画的核心逻辑,包括循环高亮、速度变化和结果控制。
  1. @Entry
  2. @Component
  3. struct LuckyDraw {
  4.   // 前面的状态变量保持不变...
  5.   // 添加动画控制相关变量
  6.   private timer: number = 0
  7.   private speed: number = 100
  8.   private totalRounds: number = 30
  9.   private currentRound: number = 0
  10.   private targetIndex: number = 2 // 假设固定中奖"优惠券"
  11.   // 开始抽奖
  12.   startLottery() {
  13.     if (this.isRunning) {
  14.       return // 防止重复点击
  15.     }
  16.     this.isRunning = true
  17.     this.result = '抽奖中...'
  18.     this.currentRound = 0
  19.     this.speed = 100
  20.     // 启动动画
  21.     this.runLottery()
  22.   }
  23.   // 运行抽奖动画
  24.   runLottery() {
  25.     if (this.timer) {
  26.       clearTimeout(this.timer)
  27.     }
  28.     this.timer = setTimeout(() => {
  29.       // 更新当前高亮的格子
  30.       this.currentIndex = (this.currentIndex + 1) % 9
  31.       if (this.currentIndex === 4) { // 跳过中间的"开始抽奖"按钮
  32.         this.currentIndex = 5
  33.       }
  34.       this.currentRound++
  35.       // 增加速度变化,模拟减速效果
  36.       if (this.currentRound > this.totalRounds * 0.7) {
  37.         this.speed += 10 // 大幅减速
  38.       } else if (this.currentRound > this.totalRounds * 0.5) {
  39.         this.speed += 5 // 小幅减速
  40.       }
  41.       // 结束条件判断
  42.       if (this.currentRound >= this.totalRounds && this.currentIndex === this.targetIndex) {
  43.         // 抽奖结束
  44.         this.isRunning = false
  45.         this.result = `恭喜获得: ${this.prizes[this.targetIndex].name}`
  46.       } else {
  47.         // 继续动画
  48.         this.runLottery()
  49.       }
  50.     }, this.speed)
  51.   }
  52.   // 组件销毁时清除定时器
  53.   aboutToDisappear() {
  54.     if (this.timer) {
  55.       clearTimeout(this.timer)
  56.       this.timer = 0
  57.     }
  58.   }
  59.   // build方法保持不变...
  60. }
复制代码
在这一步,我们实现了抽奖动画的核心逻辑:
    添加了动画控制相关变量:
      timer:用于存储定时器IDspeed:控制动画速度totalRounds:总共旋转的轮数currentRound:当前已旋转的轮数targetIndex:预设的中奖索引
    实现了 startLottery()方法:
      防止重复点击初始化抽奖状态调用 runLottery()开始动画
    实现了 runLottery()方法:
      使用 setTimeout创建循环动画更新高亮格子的索引,并跳过中间的开始按钮根据进度增加延迟时间,模拟减速效果根据条件判断是否结束动画递归调用自身形成动画循环
    添加了 aboutToDisappear()生命周期方法,确保在组件销毁时清除定时器,避免内存泄漏
完整代码

最后,我们对代码进行完善和优化,确保抽奖功能正常工作并提升用户体验。
完整的代码如下:
  1. interface PrizeItem {
  2.   id: number
  3.   name: string
  4.   icon: ResourceStr
  5.   color: string
  6. }
  7. @Entry
  8. @Component
  9. struct LuckyDraw {
  10.   // 定义奖品数组
  11.   @State prizes: PrizeItem[] = [
  12.     {
  13.       id: 1,
  14.       name: '谢谢参与',
  15.       icon: $r('app.media.startIcon'),
  16.       color: '#FF9500'
  17.     },
  18.     {
  19.       id: 2,
  20.       name: '10积分',
  21.       icon: $r('app.media.startIcon'),
  22.       color: '#34C759'
  23.     },
  24.     {
  25.       id: 3,
  26.       name: '优惠券',
  27.       icon: $r('app.media.startIcon'),
  28.       color: '#007AFF'
  29.     },
  30.     {
  31.       id: 8,
  32.       name: '1元红包',
  33.       icon: $r('app.media.startIcon'),
  34.       color: '#FF3B30'
  35.     },
  36.     {
  37.       id: 0,
  38.       name: '开始\n抽奖',
  39.       icon: $r('app.media.startIcon'),
  40.       color: '#FF2D55'
  41.     },
  42.     {
  43.       id: 4,
  44.       name: '5元红包',
  45.       icon: $r('app.media.startIcon'),
  46.       color: '#5856D6'
  47.     },
  48.     {
  49.       id: 7,
  50.       name: '免单券',
  51.       icon: $r('app.media.startIcon'),
  52.       color: '#E73C39'
  53.     },
  54.     {
  55.       id: 6,
  56.       name: '50积分',
  57.       icon: $r('app.media.startIcon'),
  58.       color: '#38B0DE'
  59.     },
  60.     {
  61.       id: 5,
  62.       name: '会员卡',
  63.       icon: $r('app.media.startIcon'),
  64.       color: '#39A5DC'
  65.     },
  66.   ]
  67.   // 当前高亮的奖品索引
  68.   @State currentIndex: number = -1
  69.   // 是否正在抽奖
  70.   @State isRunning: boolean = false
  71.   // 中奖结果
  72.   @State result: string = '点击下方按钮开始抽奖'
  73.   // 动画定时器
  74.   private timer: number = 0
  75.   // 动画速度控制
  76.   private speed: number = 100
  77.   private totalRounds: number = 30
  78.   private currentRound: number = 0
  79.   // 预设中奖索引(可以根据概率随机生成)
  80.   private targetIndex: number = 2 // 假设固定中奖"优惠券"
  81.   // 开始抽奖
  82.   startLottery() {
  83.     if (this.isRunning) {
  84.       return
  85.     }
  86.     this.isRunning = true
  87.     this.result = '抽奖中...'
  88.     this.currentRound = 0
  89.     this.speed = 100
  90.     // 启动动画
  91.     this.runLottery()
  92.   }
  93.   // 运行抽奖动画
  94.   runLottery() {
  95.     if (this.timer) {
  96.       clearTimeout(this.timer)
  97.     }
  98.     this.timer = setTimeout(() => {
  99.       // 更新当前高亮的格子
  100.       this.currentIndex = (this.currentIndex + 1) % 9
  101.       if (this.currentIndex === 4) { // 跳过中间的"开始抽奖"按钮
  102.         this.currentIndex = 5
  103.       }
  104.       this.currentRound++
  105.       // 增加速度变化,模拟减速效果
  106.       if (this.currentRound > this.totalRounds * 0.7) {
  107.         this.speed += 10
  108.       } else if (this.currentRound > this.totalRounds * 0.5) {
  109.         this.speed += 5
  110.       }
  111.       // 结束条件判断
  112.       if (this.currentRound >= this.totalRounds && this.currentIndex === this.targetIndex) {
  113.         // 抽奖结束
  114.         this.isRunning = false
  115.         this.result = `恭喜获得: ${this.prizes[this.targetIndex].name}`
  116.       } else {
  117.         // 继续动画
  118.         this.runLottery()
  119.       }
  120.     }, this.speed)
  121.   }
  122.   // 组件销毁时清除定时器
  123.   aboutToDisappear() {
  124.     if (this.timer) {
  125.       clearTimeout(this.timer)
  126.       this.timer = 0
  127.     }
  128.   }
  129.   build() {
  130.     Column({ space: 30 }) {
  131.       // 标题
  132.       Text('幸运抽奖')
  133.         .fontSize(24)
  134.         .fontWeight(FontWeight.Bold)
  135.         .fontColor(Color.White)
  136.       // 结果显示
  137.       Column() {
  138.         Text(this.result)
  139.           .fontSize(20)
  140.           .fontColor(Color.White)
  141.       }
  142.       .width('90%')
  143.       .padding(15)
  144.       .backgroundColor('#0DFFFFFF')
  145.       .borderRadius(16)
  146.       // 九宫格抽奖区域
  147.       Grid() {
  148.         ForEach(this.prizes, (prize: PrizeItem, index) => {
  149.           GridItem() {
  150.             Column() {
  151.               if (index === 4) {
  152.                 // 中间的开始按钮
  153.                 Button({ type: ButtonType.Capsule }) {
  154.                   Text(prize.name)
  155.                     .fontSize(18)
  156.                     .fontWeight(FontWeight.Bold)
  157.                     .textAlign(TextAlign.Center)
  158.                     .fontColor(Color.White)
  159.                 }
  160.                 .width('90%')
  161.                 .height('90%')
  162.                 .backgroundColor(prize.color)
  163.                 .onClick(() => this.startLottery())
  164.               } else {
  165.                 // 普通奖品格子
  166.                 Image(prize.icon)
  167.                   .width(40)
  168.                   .height(40)
  169.                 Text(prize.name)
  170.                   .fontSize(14)
  171.                   .fontColor(index === this.currentIndex && index !== 4 ? prize.color : Color.White)
  172.                   .margin({ top: 8 })
  173.                   .textAlign(TextAlign.Center)
  174.               }
  175.             }
  176.             .width('100%')
  177.             .height('100%')
  178.             .justifyContent(FlexAlign.Center)
  179.             .alignItems(HorizontalAlign.Center)
  180.             .backgroundColor(index === this.currentIndex && index !== 4 ? Color.White : prize.color)
  181.             .borderRadius(12)
  182.             .padding(10)
  183.             .animation({
  184.               duration: 200,
  185.               curve: Curve.EaseInOut
  186.             })
  187.           }
  188.         })
  189.       }
  190.       .columnsTemplate('1fr 1fr 1fr')
  191.       .rowsTemplate('1fr 1fr 1fr')
  192.       .columnsGap(10)
  193.       .rowsGap(10)
  194.       .width('90%')
  195.       .aspectRatio(1)
  196.       .backgroundColor('#0DFFFFFF')
  197.       .borderRadius(16)
  198.       .padding(10)
  199.     }
  200.     .width('100%')
  201.     .height('100%')
  202.     .justifyContent(FlexAlign.Center)
  203.     .backgroundColor(Color.Black)
  204.     .linearGradient({
  205.       angle: 135,
  206.       colors: [
  207.         ['#121212', 0],
  208.         ['#242424', 1]
  209.       ]
  210.     })
  211.     .expandSafeArea() // 颜色扩展到安全区域
  212.   }
  213. }
复制代码
核心概念解析

1. Grid组件

Grid组件是实现九宫格布局的核心,它具有以下重要属性:
    columnsTemplate:定义网格的列模板。'1fr 1fr 1fr'表示三列等宽布局。rowsTemplate:定义网格的行模板。'1fr 1fr 1fr'表示三行等高布局。columnsGap和 rowsGap:设置列和行之间的间距。aspectRatio:设置宽高比,确保网格是正方形。
2. 动画实现原理

抽奖动画的核心是通过定时器和状态更新实现的:
    循环高亮:通过 setTimeout定时更新 currentIndex状态,实现格子的循环高亮。动态速度:随着循环轮数的增加,逐渐增加延迟时间(this.speed += 10),实现减速效果。结束条件:当满足两个条件时停止动画:
      已完成设定的总轮数(this.currentRound >= this.totalRounds)当前高亮的格子是目标奖品(this.currentIndex === this.targetIndex)

3. 高亮效果

格子的高亮效果是通过条件样式实现的:
  1. .backgroundColor(index === this.currentIndex && index !== 4 ? Color.White : prize.color)
复制代码
当格子被选中时(index === this.currentIndex),背景色变为白色,文字颜色变为奖品颜色,产生对比鲜明的高亮效果。
4. 资源清理

在组件销毁时,我们需要清除定时器以避免内存泄漏:
  1. aboutToDisappear() {
  2.   if (this.timer) {
  3.     clearTimeout(this.timer)
  4.     this.timer = 0
  5.   }
  6. }
复制代码
进阶优化思路

完成基本功能后,可以考虑以下优化方向:
1. 随机中奖结果

目前中奖结果是固定的,可以实现一个随机算法,根据概率分配不同奖品:
  1. // 根据概率生成中奖索引
  2. generatePrizeIndex() {
  3.   // 定义各奖品的概率权重
  4.   const weights = [50, 10, 5, 3, 0, 2, 1, 8, 20]; // 数字越大概率越高
  5.   const totalWeight = weights.reduce((a, b) => a + b, 0);
  6.   // 生成随机数
  7.   const random = Math.random() * totalWeight;
  8.   // 根据权重决定中奖索引
  9.   let currentWeight = 0;
  10.   for (let i = 0; i < weights.length; i++) {
  11.     if (i === 4) continue; // 跳过中间的"开始抽奖"按钮
  12.     currentWeight += weights[i];
  13.     if (random < currentWeight) {
  14.       return i;
  15.     }
  16.   }
  17.   return 0; // 默认返回第一个奖品
  18. }
复制代码
2. 抽奖音效

添加音效可以提升用户体验:
  1. // 播放抽奖音效
  2. playSound(type: 'start' | 'running' | 'end') {
  3.   // 根据不同阶段播放不同音效
  4. }
复制代码
3. 振动反馈

在抽奖开始和结束时添加振动反馈:
  1. // 导入振动模块
  2. import { vibrator } from '@kit.SensorServiceKit';
  3. // 触发振动
  4. triggerVibration() {
  5.   vibrator.vibrate(50); // 振动50毫秒
  6. }
复制代码
4. 抽奖次数限制

添加抽奖次数限制和剩余次数显示:
[code]@State remainingTimes: number = 3; // 剩余抽奖次数

startLottery() {
  if (this.isRunning || this.remainingTimes

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表