[openharmony] openharmony api12+ 手写板/画板简单封装 原创 精华

第一小趴菜
发布于 2025-6-18 15:15
浏览
0收藏

前言

因为我在网上找手写板案例的时候,发现这一块部分的内容很少,或者因为版本太老而不适配现在的openharmony api版本,所以自己封装了一个简单方便的版本,当作个人笔记,后方有代码解释

完整代码

@Entry
@ComponentV2
struct Index {
  private settings: RenderingContextSettings = new RenderingContextSettings(false)
  ctx: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)

  build() {
    Column() {
      Column() {

        Canvas(this.ctx)
          .onTouch((event) => {
            let touche: TouchObject = event.touches[0]

            if (touche.type == 0) {
              this.ctx.beginPath()
              this.ctx.moveTo(touche.x, touche.y);
            } else if (touche.type == 2) {
              this.ctx.lineTo(touche.x, touche.y);
              this.ctx.stroke()
            }
          })
      }.width('100%')
      .height('90%')

      Row() {
        Button("粗细3")
          .onClick(() => {
            this.ctx.lineWidth = 3
          })
        Button("粗细5")
          .onClick(() => {
            this.ctx.lineWidth = 5
          })
        Button("粗细8")
          .onClick(() => {
            this.ctx.lineWidth = 8
          })
        Button("红")
          .onClick(() => {
            this.ctx.strokeStyle = '#ff0000'
          })
        Button("绿")
          .onClick(() => {
            this.ctx.strokeStyle = '#00ff00'
          })
        Button("蓝")
          .onClick(() => {
            this.ctx.strokeStyle = '#0000ff'
          })

      }
      .width('100%')
      .height('10%')
    }.width('100%')
    .height('100%')
  }
}

上方为画布,下方为选择粗细和线条颜色,可以根据自己的需要进行修改。
文档链接

代码解释

创建一个CanvasRenderingContext2D对象为我们的画布对象,我们画线和设置线条的颜色和粗细都是可以直接对他进行操作
比如如果想改变他的粗细,直接可以对lineWidth 进行修改,如果改变颜色就直接对strokeStyle 进行赋值
moveTo方法为路径从当前点移动到指定点,lineTo方法为从当前点到指定点进行路径连接,而stroke方法则是进行边框绘制的操作。
当然也可以进行更多的操做

效果展示

[openharmony] openharmony api12+ 手写板/画板简单封装-鸿蒙开发者社区

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
收藏
回复
举报
回复
    相关推荐