鸿蒙NEXT版实战开发:如何使用canvas绘制圆角矩形?

往期鸿蒙全套实战文章必看:(附带鸿蒙全栈学习资料)


如何使用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%')
  }
}

实现效果图如下所示:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值