如何使用canvas绘制圆角矩形

如何使用canvas绘制圆角矩形

HarmonyOS
2024-07-23 10:34:11
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
pfuchenlu

利用CanvasRenderingContext2D对象的arc绘制弧形路径,结合lineTo方法绘制直线进行封装,参考代码如下:

@Entry 
@Component 
struct Page { 
  @State message: string = 'Hello World'; 
  private readonly settings: RenderingContextSettings = new RenderingContextSettings(true); 
  private readonly ctx: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); 
 
  /** 
   * 绘制圆角矩形 
   * @param {* 必填} x x坐标 
   * @param {* 必填} y y坐标 
   * @param {* 必填} width 宽度 
   * @param {* 必填} height 高度 
   * @param {* 必填} radius 圆角半径 
   * @param {* 非必填 默认值:'#456'} strokeColor 边框颜色 
   * @param {* 非必填 无默认值} fillColor 填充颜色 
   * @param {* 非必填 默认值:[]实线} lineDash 边框样式 
   */ 
  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%') 
  } 
}
分享
微博
QQ
微信
回复
2024-07-23 18:30:12
相关问题
如何绘制圆角矩形
131浏览 • 1回复 待解决
HarmonyOS canvas支持画圆角矩形
154浏览 • 1回复 待解决
如何操作canvas重新绘制
752浏览 • 1回复 待解决
Canvas绘制内容如何动态更新
1072浏览 • 1回复 待解决
修改分段按钮样式为圆角矩形
742浏览 • 1回复 待解决
Canvas如何触发刷新重复绘制
660浏览 • 1回复 待解决
利用native接口实现一个圆角矩形
1434浏览 • 1回复 待解决
canvas怎么绘制资源目录下的图片
470浏览 • 1回复 待解决
HarmonyOS Canvas中关于绘制图片问题
50浏览 • 1回复 待解决
Canvas如何绘制app.media下面的图片?
2139浏览 • 1回复 待解决
如何使用canvas添加水印
1019浏览 • 1回复 待解决
HarmonyOS使用canvas如何使文字垂直居中
284浏览 • 1回复 待解决