
回复
本篇将带你实现一个简单的数字滚动抽奖器。用户点击按钮后,屏幕上的数字会以滚动动画的形式随机变动,最终显示一个抽奖数字。这个项目展示了如何结合定时器、状态管理和动画实现一个有趣的互动应用。
数字滚动抽奖器应用允许用户点击按钮启动数字滚动动画,最终随机显示一个中奖号码。抽奖结果通过动画和随机数结合的方式呈现,增强了应用的趣味性。
@Entry
和 @Component
装饰器Column
布局组件Text
组件用于显示滚动数字Button
组件用于用户交互@State
修饰符用于状态管理setInterval
和 clearInterval
LotteryApp
LotteryPage
LotteryPage.ets
、Index.ets
// 文件名:LotteryPage.ets
@Component
export struct LotteryPage {
@State currentNumber: number = 0; // 当前显示的数字
@State isRolling: boolean = false; // 是否正在滚动
private intervalId: number | null = null; // 定时器 ID
build() {
Column({ space: 20 }) { // 创建垂直布局容器
// 显示当前数字
Text(`${this.currentNumber}`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.fontColor(this.isRolling ? Color.Gray : Color.Blue)
.textAlign(TextAlign.Center)
.margin({ top: 30 });
// 显示猫咪图片装饰
Image($r('app.media.cat'))
.width(85)
.height(100)
.borderRadius(5)
.alignSelf(ItemAlign.Center);
// 开始或停止抽奖按钮
Button(this.isRolling ? '停止抽奖' : '开始抽奖')
.onClick(() => {
if (this.isRolling) {
this.stopRolling();
} else {
this.startRolling();
}
})
.fontSize(20)
.backgroundColor(this.isRolling ? Color.Red : Color.Green)
.fontColor(Color.White)
.width('60%')
.alignSelf(ItemAlign.Center);
}
.padding(20)
.width('100%')
.height('100%')
.alignItems(HorizontalAlign.Center);
}
// 开始滚动的方法
private startRolling() {
this.isRolling = true;
this.intervalId = setInterval(() => {
this.currentNumber = Math.floor(Math.random() * 100); // 生成 0-99 的随机数
}, 100); // 每 100 毫秒更新数字
}
// 停止滚动的方法
private stopRolling() {
this.isRolling = false;
if (this.intervalId !== null) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
}
// 文件名:Index.ets
import { LotteryPage } from './LotteryPage';
@Entry
@Component
struct Index {
build() {
Column() {
LotteryPage() // 调用抽奖页面
}
.padding(20)
}
}
效果示例:用户点击“开始抽奖”按钮后,屏幕上的数字会快速滚动;点击“停止抽奖”按钮,滚动停止并显示一个随机数字作为中奖结果。
@State currentNumber
和 @State isRolling
用于控制数字显示和滚动状态。setInterval
实现快速更新 currentNumber
,模拟滚动效果。clearInterval
确保滚动停止时清理定时器,避免资源泄漏。通过数字滚动抽奖器的实现,你学会了如何结合定时器和状态管理实现动态数字更新,并将其应用于有趣的互动场景中。此示例轻量实用,适合入门开发者实践。
在下一篇「UI互动应用篇14 - 随机颜色变化器」中,我们将探索如何通过点击按钮实现界面背景的随机颜色变化,提升用户体验。
作者:SoraLuna
链接:https://www.nutpi.net/thread?topicId=318
來源:坚果派
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。