在以下使用CanvasRenderingContext2D的arc方法绘制圆弧的过程中,无论如何修改percent的值以改变弧线的终止弧度,运行代码后都会出现一个完整的圆弧。
问题示例如下:
const FULL_CIRCLE_RADIAN = Math.PI * 2 const CHECK_GREEN = '#00CC66' @Component @Entry export struct ReceiptIcon { @State radiusPx: number = 0 percent: number = 0 @State private strokeWidth: number = 0 private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Canvas(this.context) .onSizeChange((oldValue: SizeOptions, newValue: SizeOptions) => { this.radiusPx = Math.min(Number(newValue.width ?? 0), Number(newValue.height ?? 0)) * 0.5 this.strokeWidth = this.radiusPx * 0.125 }) .onReady(() => { this.context.beginPath() this.context.strokeStyle = CHECK_GREEN this.context.lineWidth = this.strokeWidth this.context.arc( this.context.width / 2, this.context.height / 2, (this.radiusPx - this.strokeWidth * 0.5), -90, this.percent * FULL_CIRCLE_RADIAN ) this.context.stroke() this.context.beginPath() this.context.fillStyle = CHECK_GREEN this.context.fill() }) } }
将第四个参数-90改成-(π/2),对应到代码中即为-(FULL_CIRCLE_RADIAN / 4),代码修改如下所示:
const FULL_CIRCLE_RADIAN = Math.PI * 2; const CHECK_GREEN = '#00CC66'; @Entry @Component export struct ReceiptIcon { @State radiusPx: number = 0; percent: number = 0; @State private strokeWidth: number = 0; private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); build() { Canvas(this.context) .onSizeChange((oldValue: SizeOptions, newValue: SizeOptions) => { this.radiusPx = Math.min(Number(newValue.width ?? 0), Number(newValue.height ?? 0)) * 0.5; this.strokeWidth = this.radiusPx * 0.125; }) .onReady(() => { this.context.beginPath(); this.context.strokeStyle = CHECK_GREEN; this.context.lineWidth = this.strokeWidth; this.context.arc( this.context.width / 2, this.context.height / 2, (this.radiusPx - this.strokeWidth * 0.5), -(FULL_CIRCLE_RADIAN / 4), this.percent * FULL_CIRCLE_RADIAN ); this.context.stroke(); this.context.beginPath(); this.context.fillStyle = CHECK_GREEN; this.context.fill(); }); } }