往期鸿蒙全套实战文章必看:(附带鸿蒙全栈学习资料)
如何使用canvas绘制圆角矩形
利用CanvasRenderingContext2D对象的arc绘制弧形路径,结合lineTo方法绘制直线,参考代码如下:
@Entry
@Component
struct CanvasDrawRoundedRectangle {
private readonly settings: RenderingContextSettings = new RenderingContextSettings(true);
private readonly ctx: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
drawRoundRect(x: number, y: number, width: number, height: number, radius: number, strokeColor?: string,
fillColor?: string, lineDash?: []) {
strokeColor = strokeColor || '#333';
lineDash = lineDash || [];
this.ctx.beginPath();
this.ctx.setLineDash(lineDash);
// 绘制第一段圆弧路径
this.ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2);
// 绘制第一段直线路径
this.ctx.lineTo(width - radius + x, y);
// 绘制第二段圆弧路径
this.ctx.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2);
// 绘制第二段直线路径
this.ctx.lineTo(width + x, height + y - radius);
// 绘制第三段圆弧路径
this.ctx.arc(width - radius + x, height - radius + y, radius, 0, Math.PI / 2);
// 绘制第三段直线路径
this.ctx.lineTo(radius + x, height + y);
// 绘制第四段圆弧路径
this.ctx.arc(radius + x, height - radius + y, radius, Math.PI / 2, Math.PI);
// 绘制第四段直线路径
this.ctx.lineTo(x, y + radius);
// 设置画笔颜色
this.ctx.strokeStyle = strokeColor;
// 描边绘制
this.ctx.stroke();
if (fillColor) {
this.ctx.fillStyle = fillColor;
this.ctx.fill();
}
this.ctx.closePath();
}
build() {
Row() {
Column() {
Canvas(this.ctx)
.width('100%')
.height('100%')
.onReady(() => {
this.drawRoundRect(50, 50, 100, 100, 10);
})
}
.width('100%')
}
.height('100%')
}
}
实现效果图如下所示: