1 个回答

请参考如下demo 使用canvas画布组件,自定义绘制刻度能否解决您的问题

@Entry
@ComponentV2
struct IR240801094524075 {
  @Local angel: number = 0
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  private radius: number = 120;
  private centerX: number = 0;
  private centerY: number = 0;

  draw() {
    this.context.clearRect(0, 0, this.context.width, this.context.height)
    // 绘制面板
    this.context.beginPath();
    this.context.arc(this.centerX, this.centerY, this.radius, Math.PI, Math.PI * 2);
    this.context.lineWidth = 1;
    this.context.strokeStyle = 'black';
    this.context.stroke();

    // 绘制刻度
    for (let i = 90; i <= 270; i += 5) {
      this.context.beginPath()
      this.context.lineWidth = 1
      this.context.strokeStyle = 'red'
      this.context.moveTo(this.centerX + this.radius * Math.sin(i / 180 * Math.PI),
        this.centerY + this.radius * Math.cos(i / 180 * Math.PI))
      this.context.lineTo(this.centerX + (this.radius - 3) * Math.sin(i / 180 * Math.PI),
        this.centerY + (this.radius - 3) * Math.cos(i / 180 * Math.PI))
      this.context.stroke()
    }

    // 绘制指针
    this.context.beginPath()
    this.context.strokeStyle = 'green'
    this.context.fillStyle = '#8000ff00'
    this.context.moveTo(this.centerX, this.centerY)
    this.context.lineTo(0, this.centerY)
    this.context.arc(this.centerX, this.centerY, this.radius, Math.PI, Math.PI * (1 + this.angel / 180))
    this.context.lineTo(this.centerX, this.centerY)
    this.context.stroke()
    this.context.fill()
  }

  build() {
    Column() {
      Canvas(this.context)
        .width(300)
        .height(150)
        .backgroundColor(Color.Pink)
        .onReady(() => {
          this.centerX = this.context.width / 2
          this.centerY = this.context.height

          this.draw()
        })
        .onTouch((event) => {
          let x = this.centerX - event.touches[0].x
          let y = this.centerY - event.touches[0].y
          this.angel = Math.atan(y / x) * (180 / Math.PI)
          if (this.angel < 0) {
            // 表示钝角
            this.angel += 180
          }
          this.draw()
        })
      Text('当前角度:' + this.angel.toFixed(2))
    }.width("100%").height("100%").justifyContent(FlexAlign.Center).alignItems(HorizontalAlign.Center)
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进