9. 电阻分压原理

场景:通过滑动变阻器直观展示电压分配关系。
核心逻辑:动态计算并显示两个电阻上的电压值。

@Entry
@Component
struct VoltageDivider {
  @State r1: number = 50 // R1阻值
  @State r2: number = 50 // R2阻值

  build() {
    Column({ space: 30 }) {
      // 可视化电阻条
      Row() {
        Column()
          .layoutWeight(this.r1)
          .height(40)
          .backgroundColor(Color.Blue)
        Column()
          .layoutWeight(this.r2)
          .height(40)
          .backgroundColor(Color.Red)
      }
      .width('80%')
      .borderWidth(2)

      Text(`总电压: 10V`)
      Text(`R1电压: ${(10 * this.r1 / (this.r1 + this.r2)).toFixed(2)}V`).fontColor(Color.Blue)
      Text(`R2电压: ${(10 * this.r2 / (this.r1 + this.r2)).toFixed(2)}V`).fontColor(Color.Red)

      Row() {
        Text('R1: ')
        Slider({ value: this.r1, min: 10, max: 100 })
          .layoutWeight(1)
          .onChange((v) => this.r1 = v)
      }
      Row() {
        Text('R2: ')
        Slider({ value: this.r2, min: 10, max: 100 })
          .layoutWeight(1)
          .onChange((v) => this.r2 = v)
      }
    }
    .width('100%')
    .height('100%')
    .padding(20)
    .justifyContent(FlexAlign.Center)
  }
}
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐