HarmonyOS 如何实现自定义圆环进度条?

如题:HarmonyOS 如何实现自定义圆环进度条?

阅读 572
1 个回答

可参考如下代码实现圆环进度条效果:

/**
 * 用画布画弧形的进度条
 */
@Entry
@Component
struct Arc {
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600)

  @State @Watch('onCountUpdated') radianTest :number = 0
  @State color:string="#ff8c909b" //"#ff144cd2"
  onCountUpdated(): void {
    this.test()
  }
  test=():void=>{
    let offContext = this.offCanvas.getContext("2d", this.settings)
    offContext.lineCap = "round"
    offContext.lineWidth=8
    offContext.beginPath()
    offContext.arc(
      100,
      75,
      50,
      (225-90) * Math.PI / 180,
      (135-90) * Math.PI / 180
    )
    offContext.strokeStyle = "#ff8c909b"
    offContext.stroke()

    offContext.beginPath()
    offContext.arc(
      100,
      75,
      50,
      (225 - 90) * (Math.PI / 180),
      this.radianTest===0?(135 - 90) * (Math.PI / 180):(135 - 270 * (1 -this.radianTest) - 90) * (Math.PI / 180),

    )
    offContext.strokeStyle = this.color
    offContext.stroke()
    let image = this.offCanvas.transferToImageBitmap()
    this.context.transferFromImageBitmap(image)
  }

  build() {
    Column(){
      Canvas(this.context)
        .width('100%')
        .height('100%')
        .backgroundColor('#ffff00')
        .onReady(
          this.test
        )

      Button('test')
        .onClick(()=>{
          this.color = "#ff144cd2"
          this.radianTest = Number(this.radianTest+0.01)

          if(this.radianTest>1){
            this.radianTest=0
          }
        })
    }
    .width('100%')
    .height(500)
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进