1.功能
可实现风扇的正转、暂停、反转和调速控制。
2.相关知识
学习定时器、组件属性、滑动条的使用。
3.运行效果图
4.源码
@Entry
@Component
struct MainPage {
@State angleA: number = 0
@State intervalId: number = -123456;
@State dir: number = 1;
@State N: number = 1
@State lightState: boolean = false
@State focus:number=1
startTimer(): void {
this.intervalId = setInterval(() => {
if (this.dir == 1) this.angleA = this.angleA;
if (this.dir == 0) this.angleA = this.angleA + this.N;
if (this.dir == 2) this.angleA = this.angleA - this.N;
}, 10);
}
build() {
Column({ space: 5 }) {
Image($rawfile(“fan.png”))
.width(‘200vp’)
.height(‘200vp’)
.margin({ top: 30 })
.rotate({ // 中心旋转
x: 0, y: 0, z: 1,
angle: this.angleA,
})
.onAppear(() => {
this.startTimer()
})
Row() {
Text(“正转”).fontSize(‘30fp’).fontColor(this.focus0?‘#ff0000’: ‘#ff0b0c0b’)
.width(‘20%’).onClick(() => {
this.dir = 0
this.focus=0
})
Text(“停止”).fontSize(‘30fp’).fontColor(this.focus1?‘#ff0000’:‘#ff0b0c0b’)
.width(‘20%’).onClick(() => {
this.dir = 1
this.focus=1
})
Text(“反转”).fontSize(‘30fp’).fontColor(this.focus==2?‘#ff0000’:‘#ff0b0c0b’)
.width(‘20%’).onClick(() => {
this.dir = 2
this.focus=2
})
}.justifyContent(FlexAlign.SpaceEvenly)
Row() {
Text("0").fontSize(20)
Slider({
value: this.N,
min: 0,
max: 10,
step: 1,
style: SliderStyle.OutSet,
direction: Axis.Horizontal,
reverse: false
})
.width('80%')
.height(40)
.backgroundColor("#ffcbcbcf")
.blockColor(Color.Red)// 设置滑块颜色
.trackColor(Color.Pink)// 设置滑轨颜色
.selectedColor(Color.Red)// 设置滑轨的已滑动颜色
.trackThickness(6)// 设置滚动条宽度
.onChange((value: number) => {
this.N = value
})
Text("10").fontSize(20)
}
}.backgroundColor("#ccff33").height('100%').width('100%')
}
}