使用Canvas画布组件,自定义绘制带有刻度的环形图表。具体实现步骤如下:
@Entry @ComponentV2 struct GaugeScale { @Local angle: 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.angle / 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; if (y >= 0) { this.angle = Math.atan(y / x) * (180 / Math.PI); if (this.angle < 0) { // 表示钝角 this.angle += 180; } this.draw(); } else if (x < 0 && y < 0 && this.angle != 0) { this.angle = 180; this.draw(); } else if (x > 0 && y < 0 && this.angle != 180) { this.angle = 0; this.draw(); } }); Text('当前角度:' + this.angle.toFixed(2)); }.width('100%').height('100%').justifyContent(FlexAlign.Center).alignItems(HorizontalAlign.Center); } }