用的ArkTS
interface Student{
id:number
name:string
url:string
count:number
}
@Entry
@Component
struct Index{
@State flag:number=1
@State randomIndex:number=-1//表示还没开始点名
@State name:string=""//名字
@State studentArray:Student[]=[
{id:1,name:"张三",url:'app.media.picture0',count:0},
{id:2,name:"李四",url:'app.media.picture1',count:0},
{id:3,name:"王五",url:'app.media.picture2',count:0},
{id:4,name:"王五",url:'app.media.picture3',count:0},
{id:5,name:"王五",url:'app.media.picture4',count:0},
{id:6,name:"丽丽",url:'app.media.picture5',count:0},
]
//遮罩参数
@State maskOpacity:number=0//透明度
@State maskZIndex:number=-1//显示层级
//控制图片缩放
@State maskImgX:number=0//水平缩放比
@State maskImgY:number=0//垂直缩放比
build() {
Column(){
Stack() {
Column() {
Text("班级成员")
.fontSize(40)
.width(200)
.margin({ top: 20 })
Grid() {
ForEach(this.studentArray, (item: Student, index: number) => {
GridItem() {
Badge({
count: item.count,
position: BadgePosition.RightTop,
style: {
fontSize: 14,
badgeSize: 20,
badgeColor: '#fa2a2d'
}
}) {
Image($r(item.url))
.width(100)
.height(100)
}
}
})
}
.columnsTemplate('1fr 1fr 1fr')
.rowsTemplate('1fr 1fr')
.width('100%')
.height(300)
.margin({ top: 20 })
}
Button('开始点名')
.width(200)
.backgroundColor('#ed5b8c')
.margin({ top: 50 })
.onClick(() => {
//点击时,修改遮罩参数,让遮罩显示
this.maskOpacity = 1
this.maskZIndex = 99
//点击时,图片需要缩放
this.maskImgX = 1
this.maskImgY = 1
//生成随机数Math.random()
this.flag = 2;
this.randomIndex = Math.floor(Math.random() * 6)
if (this.studentArray[this.randomIndex].count) {
for (let item of this.studentArray) {
if (item.count) {
this.flag = 2
this.randomIndex = item.id - 1
break}
else
this.flag = 1
}
}
if (this.flag == 2)
this.name = this.studentArray[this.randomIndex].name
else this.name = "班级成员全部点完名字"
})
// console.log(studentArray[randomIndex].name)
// console.log("随机")
}
.width('100%')
.height('100%')
//抽卡遮罩层
Column({ space: 30 }) {
Text('幸运星')
.fontColor('#f5ebcf')
.fontSize(25)
.fontWeight(FontWeight.Bold)
Text(this.name)
.fontColor('#f5ebcf')
.fontSize(25)
.fontWeight(FontWeight.Bold)
Image($r(`app.media.picture${this.randomIndex}`))
.width(200)//控制元素缩放
.scale({
x: this.maskImgX,
y: this.maskImgY
})
.animation({ duration: 500 })
Button('重新点名')
.width(200)
.height(50)
.backgroundColor(Color.Transparent)
.border({ width: 2, color: '#fff9e0' })
.onClick(() => {
//控制弹窗显影
this.maskOpacity=0
this.maskZIndex=-1
//图像重置缩放比为0
this.maskImgX=0
this.maskImgY=0
//对象数组情况需要更新,需要修改替换整个对象
this.studentArray[this.randomIndex]={
id:this.studentArray[this.randomIndex].id,
name:this.studentArray[this.randomIndex].name,
url:`app.media.picture${this.randomIndex}`,
count:this.studentArray[this.randomIndex].count+1,
}
})
}
.justifyContent(FlexAlign.Center)
.width('100%')
.height('100%')
.backgroundColor('#cc000000')
//设置透明度
.opacity(this.maskOpacity)
.zIndex(this.maskZIndex)
//动画
.animation({duration:200})
}
}}
按按钮之前
按按钮之后