简单的绘图板有人知道方法吗?

简单的绘图板


HarmonyOS
2024-05-21 21:56:08
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
kraml

本文通过命令模式在HarmonyOS上实现一个简单的绘图板,该绘图板功能比较简单,只能以触点轨迹绘制线条。

使用的核心API

CanvasRenderingContext2D

Path2D

核心代码解释

首先我们声明一个抽象接口IBrush,用它定义不同笔触需要实现的方法。

export interface IBrush { 
  
  /** 
   * 触电接触时 
   */ 
  down(path:Path2D,x:number,y:number); 
  
  /** 
   * 触电移动时 
   */ 
  move(path:Path2D,x:number,y:number); 
  
  /** 
   * 触点停止时 
   * @param x 
   * @param y 
   */ 
  up(path:Path2D,x:number,y:number); 
}

为了方便,这里只定义普通的笔触。

export default class NormalBrush  implements IBrush{ 
  
  down(path: Path2D, x: number, y: number) { 
    path.moveTo(x,y); 
  } 
  
  move(path: Path2D, x: number, y: number) { 
    path.lineTo(x,y); 
  } 
  
  up(path: Path2D, x: number, y: number) { 
  
  } 
}

对于每一次的绘制,都可以有两个命令,一个是绘制命令,另一个是撤销命令,我们将其封装为一个命令接口。

export interface IDraw { 
  
  /** 
   * 绘制命令 
   */ 
  draw(context: CanvasRenderingContext2D):void; 
  
  /** 
   * 撤销命令 
   */ 
  unDo():void; 
}

这里只绘制路劲一种方法。

import { IDraw } from './IDraw'; 
import Paint from './Paint'; 
  
/** 
 * 绘制的路径 
 */ 
export default class DrawPath implements IDraw{ 
  
  public paint:Paint;//绘制画笔 
  public path:Path2D;//绘制的路径 
  
  draw(context: CanvasRenderingContext2D) { 
    context.lineWidth = this.paint.lineWidth; 
    console.info('DrawPath == '+this.paint.strokeStyle) 
    context.strokeStyle = this.paint.strokeStyle 
    context.stroke(this.path) 
  } 
  
  unDo() { 
  
  } 
  
}

虽然只有一个绘制路劲的命令,但是,我们为其提供下撤销和重做的功能,因此,依然需要一个请求者角色来对命令进一步封装。

import List from '@ohos.util.List'; 
import DrawPath from './DrawPath'; 
  
export default class DrawInvoker { 
  
  //绘制列表 
  private drawPathList:List<DrawPath> = new List<DrawPath>(); 
   
  //重做列表 
  private redoList:List<DrawPath> = new List<DrawPath>(); 
  
  /** 
   * 添加绘制路径 
   */ 
  add(command:DrawPath):void{ 
    this.redoList.clear(); 
    this.drawPathList.add(command); 
  } 
  
  /** 
   * 撤销上一步命令 
   */ 
  undo() :void{ 
    if(this.drawPathList.length > 0) { 
      let undo:DrawPath = this.drawPathList.get(this.drawPathList.length -1); 
      this.drawPathList.removeByIndex(this.drawPathList.length-1); 
      //撤销 
      undo.unDo(); 
      this.redoList.add(undo); 
    } 
  } 
  
  /** 
   * 重做上一步命令 
   */ 
  redo() :void{ 
    if(this.redoList.length > 0) { 
      let redoCommand = this.redoList.get(this.redoList.length -1); 
      this.redoList.removeByIndex(this.redoList.length-1); 
      this.drawPathList.add(redoCommand); 
    } 
  } 
  
  //执行命令 
  execute(context: CanvasRenderingContext2D) { 
    //进行绘制 
    if(this.drawPathList != null) { 
      this.drawPathList.forEach(element => { 
        element.draw(context) 
      }); 
    } 
  } 
  
  /** 
   * 是否可以重做 
   */ 
  canRedo():boolean { 
    return this.redoList.length > 0; 
  } 
  
  /** 
   * 是否可以撤销 
   */ 
  canUndo() { 
    return this.drawPathList.length > 0; 
  } 
  
}

然后就是在page完成绘画板功能

import CircleBrush from '../draw/CircleBrush'; 
import DrawInvoker from '../draw/DrawInvoker' 
import DrawPath from '../draw/DrawPath'; 
import { IBrush } from '../draw/IBrush'; 
import NormalBrush from '../draw/NormalBrush'; 
import Paint from '../draw/Paint'; 
  
@Entry 
@Component 
export struct DrawCanvas { 
  @State @Watch('createDraw')isDrawing:boolean = false //标识是否可以绘制 
  @State unDoDraw:boolean = false;//撤销操作 
  @State redoDraw:boolean = false;//重做操作 
  @State drawHeight:number = undefined; 
  @State drawWidth:number = undefined; 
  private settings: RenderingContextSettings = new RenderingContextSettings(true) 
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) 
  private drawInvoker:DrawInvoker = new DrawInvoker(); 
  private path2Db: Path2D = new Path2D() 
  private mPaint:Paint = undefined;//画笔对象 
  private mPath:DrawPath = undefined;//绘制路径 
  private mBrush:IBrush = undefined;//笔触对象 
  
  
  /** 
   * 默认为黑色 
   */ 
  async aboutToAppear() { 
    this.mPaint = new Paint(); 
    this.mPaint.setStrokeWidth(3); 
    this.mPaint.setColor('black') 
    this.mBrush = new NormalBrush(); 
  } 
  
  /** 
   * 添加一条绘制路径 
   * @param path 
   */ 
  add(path:DrawPath):void { 
    this.drawInvoker.add(path); 
  } 
  
  /** 
   * 重做上一步撤销的绘制 
   */ 
  redo():void { 
    this.drawInvoker.redo(); 
    this.isDrawing = true; 
  } 
  
  /** 
   * 撤销上一步 
   */ 
  unDo() { 
    this.drawInvoker.undo(); 
    this.isDrawing = true 
  } 
  
  /** 
   * 是否可以撤销 
   */ 
  canUnDo() :boolean { 
    return this.drawInvoker.canUndo(); 
  } 
  
  /** 
   * 是否可以重做 
   */ 
  canRedo():boolean { 
    return this.drawInvoker.canRedo(); 
  } 
  
  createDraw() { 
    //绘制背景 
    if(this.isDrawing) { 
      //从新绘制画板颜色,从而到达重新绘制效果 
      this.context.fillStyle = '#ffff00' 
      this.context.fillRect(0,0,this.context.width,this.context.height); 
      this.drawInvoker.execute(this.context) 
      this.isDrawing = false; 
    } 
  } 
  
  onTouchListener(event: TouchEvent) { 
    if (event.type === TouchType.Down) { 
      this.mPath = new DrawPath(); 
      this.mPath.paint = this.mPaint; 
      console.info('onTouchListener DrawPath == '+this.mPath.paint.strokeStyle) 
      this.mPath.path = new Path2D(); 
      this.mBrush.down(this.mPath.path,event.touches[0].x,event.touches[0].y) 
    } 
    if (event.type === TouchType.Up) { 
      this.mBrush.up(this.mPath.path,event.touches[0].x,event.touches[0].y) 
      //添加路径 
      this.add(this.mPath); 
      this.isDrawing = true; 
      this.redoDraw = false; 
      this.unDoDraw = true; 
    } 
    if (event.type === TouchType.Move) { 
      this.mBrush.move(this.mPath.path,event.touches[0].x,event.touches[0].y) 
    } 
  } 
  
  /** 
   * 切换红色笔 
   */ 
  drawRedOnClick() { 
    this.mPaint = new Paint(); 
    this.mPaint.setStrokeWidth(3); 
    this.mPaint.setColor('red') 
  } 
  
  /** 
   * 切换绿色 
   */ 
  drawGreenOnClick() { 
    this.mPaint = new Paint(); 
    this.mPaint.setStrokeWidth(3); 
    this.mPaint.setColor('green') 
  } 
  
  /** 
   * 切换为蓝色 
   */ 
  drawBlueOnClick() { 
    this.mPaint = new Paint(); 
    this.mPaint.setStrokeWidth(3); 
    this.mPaint.setColor('blue') 
  } 
  
  /** 
   * 原型笔触 
   */ 
  drawBrushCircle() { 
    this.mBrush = new CircleBrush(); 
  } 
  
  /** 
   * 正常笔触 
   */ 
  drawBrushNormal() { 
    this.mBrush = new NormalBrush(); 
  } 
  
  /** 
   * 撤销操作 
   */ 
  drawOperateUndo() { 
    this.unDo(); 
    if(!this.canUnDo()) { 
      this.unDoDraw = false 
    } 
    this.redoDraw = true; 
  } 
  
  /** 
   * 重做操作 
   */ 
  drawOperateRedo() { 
    this.redo(); 
    if(!this.canRedo()) { 
      this.redoDraw = false; 
    } 
    this.unDoDraw = true; 
  } 
  
  build(){ 
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 
      Canvas(this.context) 
        .width('100%') 
        .height('100%') 
        .backgroundColor('#ffff00') 
        .onTouch(this.onTouchListener.bind(this)) 
        .width('100%') 
        .layoutWeight(1) 
      Column() { 
        Row() { 
          Button('红色', { type: ButtonType.Normal, stateEffect: true }) 
            .borderRadius(8) 
            .backgroundColor(0x317aff) 
            .height(60) 
            .margin({right:4}) 
            .layoutWeight(1) 
            .onClick(() => { 
              this.drawRedOnClick(); 
            }) 
  
          Button('绿色', { type: ButtonType.Normal, stateEffect: true }) 
            .borderRadius(8) 
            .backgroundColor(0x317aff) 
            .layoutWeight(1) 
            .margin({left:4,right:4}) 
            .height(60) 
            .onClick(() => { 
              this.drawGreenOnClick(); 
            }) 
  
          Button('蓝色', { type: ButtonType.Normal, stateEffect: true }) 
            .borderRadius(8) 
            .backgroundColor(0x317aff) 
            .layoutWeight(1) 
            .margin({left:4,right:4}) 
            .height(60) 
            .onClick(() => { 
              this.drawBlueOnClick(); 
            }) 
        } 
        .width('90%') 
        .margin({top:8,bottom:4}) 
        .alignItems(VerticalAlign.Center) 
  
        Row() { 
          Button('普通笔刷', { type: ButtonType.Normal, stateEffect: true }) 
            .borderRadius(8) 
            .backgroundColor(0x317aff) 
            .height(60) 
            .margin({right:4}) 
            .layoutWeight(1) 
            .onClick(async () => { 
              this.drawBrushNormal(); 
            }) 
  
          Button('圆形笔刷', { type: ButtonType.Normal, stateEffect: true }) 
            .borderRadius(8) 
            .backgroundColor(0x317aff) 
            .layoutWeight(1) 
            .margin({left:4,right:4}) 
            .height(60) 
            .onClick(async () => { 
              this.drawBrushCircle(); 
            }) 
        } 
        .margin({top:4,bottom:4}) 
        .width('90%') 
        .alignItems(VerticalAlign.Center) 
        Row() { 
          Button('撤销', { type: ButtonType.Normal, stateEffect: true }) 
            .borderRadius(8) 
            .backgroundColor(0x317aff) 
            .height(60) 
            .margin({right:4}) 
            .enabled(this.unDoDraw) 
            .layoutWeight(1) 
            .onClick(async () => { 
              this.drawOperateUndo(); 
            }) 
  
          Button('重绘', { type: ButtonType.Normal, stateEffect: true }) 
            .borderRadius(8) 
            .backgroundColor(0x317aff) 
            .layoutWeight(1) 
            .enabled(this.redoDraw) 
            .margin({left:4,right:4}) 
            .height(60) 
            .onClick(async () => { 
              this.drawOperateRedo(); 
            }) 
  
        } 
        .width('90%') 
        .margin({top:4,bottom:8}) 
        .alignItems(VerticalAlign.Center) 
      } 
    } 
    .width('100%') 
    .height('100%') 
  } 
}

实现效果

适配的版本信息

IDE:DevEco Studio 4.0.1.501

SDK:HarmoneyOS 4.0.0.8

分享
微博
QQ
微信
回复
2024-05-22 17:43:26
相关问题
弧形进度条实现,有人知道方法
322浏览 • 1回复 待解决
图片压缩并保存方法有人知道
319浏览 • 0回复 待解决
taskpool 使用问题,有人知道
390浏览 • 1回复 待解决
webview组件demo ,有人知道
418浏览 • 1回复 待解决
有人知道社区怎么预约直播
1257浏览 • 1回复 已解决
如何跳出ForEach,有人知道
593浏览 • 1回复 待解决
如何保存faultLogger ,有人知道
147浏览 • 1回复 待解决
SnapShot定位,有人知道怎么处理
379浏览 • 1回复 待解决
有人知道JS menu如何隐藏
3089浏览 • 1回复 待解决
如何发送短信,有人知道?
553浏览 • 1回复 待解决
有人知道关于页demo
390浏览 • 1回复 待解决
List组件性能问题,有人知道
590浏览 • 1回复 待解决
有人知道如何实现图文混排
341浏览 • 1回复 待解决
如何使用快速修复,有人知道
226浏览 • 1回复 待解决
如何引用HSP库,有人知道?
551浏览 • 1回复 待解决
如何实现翻页功能,有人知道
576浏览 • 1回复 待解决
导航栏如何适配,有人知道?
558浏览 • 0回复 待解决
ArkTS支持反射,有人知道反射用法?
704浏览 • 1回复 待解决
如何定义dialog动画,有人知道?
698浏览 • 1回复 待解决
新人求简单封装方法
3190浏览 • 1回复 待解决
读取文件流方式,有人知道
450浏览 • 1回复 待解决
有人知道发布页demo
423浏览 • 1回复 待解决
clientid相关问题,有人知道
453浏览 • 1回复 待解决