当系统布局无法满足需求的时候,就需要自己绘制了,我的需求是绘制如下图,且跟跟随上下滑动调整凹形大小。

snapshot_2024-11-11_10-33-59 拷贝.png
布局分析
对关键点拆分如下图:

image.png
- 三个一样大小的圆
 
- 进行外切
 
- 中间的凹形
 
- DG弧度绘制
 - AD/GE弧度绘制
 
- 上下滑动凹形大小尺寸变化
 
- 通过官网查询,最合适是使用
Canvas,但Canvas.onReady只绘制一次,可以通过@Watch监听变量(圆的直径)大小变化解决 
用到的知识
1. 勾股定理
在平面上的一个直角三角形中,两个直角边边长的平方加起来等于斜边长的平方。如果设直角三角形的两条直角边长度分别是和,斜边长度是,那么可以用数学语言表达:

image.png
2. 弧度与角度转化
弧度与角度转换公式
1)将弧度转换为角度:乘以 180,除以 π
2)将角度转换为弧度:乘以 π,除以 180
这是弧度与角度的对照列表:
| 角度 | 弧度(精确) | 弧度(近似) | 
|---|---|---|
| 30° | π/6 | 0.524 | 
| 45° | π/4 | 0.785 | 
| 60° | π/3 | 1.047 | 
| 90° | π/2 | 1.571 | 
| 180° | π | 3.142 | 
| 270° | 3π/2 | 4.712 | 
| 360° | 2π | 6.283 | 
布局开始绘制
对于以上的布局分析,可以知道,布局绘制,其实画三个弧线就可以完成了,代码如下:
// AD左上弧-起始角度270,终点角度330
this.context.arc(centerX - mar, radius, radius, 270 * Math.PI / 180, 330 * Math.PI / 180)
// DG底部弧-起始角度150,终点角度30
this.context.arc(centerX, 0, radius, 150 * Math.PI / 180, 30 * Math.PI / 180, true)
// GE右上弧-起始角度210,终点角度270
this.context.arc(centerX + mar, radius, radius, 210 * Math.PI / 180, 270 * Math.PI / 180)
完整代码如下
// 上下滑动修改fabSize的大小,使Canvas重新绘制
@State @Watch('drawBottomBar') fabSize: number = 80
drawBottomBar() {
    let width = this.context.width
    let height = this.context.height
    // 删除之前绘制的,重新绘制
    this.context.clearRect(0, 0, width, height)
    this.context.beginPath()
    let centerX = width / 2
    let radius = this.fabSize / 2
    // AB/BE的距离
    let mar = Math.sqrt(Math.pow(this.fabSize, 2) - Math.pow(radius, 2))
    // 左上直线
    this.context.lineTo(centerX - mar, 0)
    // AD左上弧-起始角度270,终点角度330
    this.context.arc(centerX - mar, radius, radius, 270 * Math.PI / 180, 330 * Math.PI / 180)
    // DG底部弧-起始角度150,终点角度30
    this.context.arc(centerX, 0, radius, 150 * Math.PI / 180, 30 * Math.PI / 180, true)
    // GE右上弧-起始角度210,终点角度270
    this.context.arc(centerX + mar, radius, radius, 210 * Math.PI / 180, 270 * Math.PI / 180)
    // 右上直线
    this.context.lineTo(width, 0)
    // 右下直线
    this.context.lineTo(width, height)
    // 底部直线
    this.context.lineTo(0, height)
    // 闭合
    this.context.closePath()
    // 颜色
    this.context.fillStyle = '#344955'
    // 填充
    this.context.fill()
}
build() {
    Stack() {
      Canvas(this.context)
        .height(80)
        .width('100%')
        .onReady(() => {
          this.drawBottomBar()
        })
    }
}