#鸿蒙通关秘籍#如何使用NodeContainer实现手写绘制功能

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
NLP苍梧巅

实现手写绘制功能需要借助NodeContainer组件,以下是实现步骤:

  1. 创建MyNodeController类继承NodeController,用于获取根节点的RenderNode和NodeContainer组件的宽高。确保NodeContainer在布局时设置背景色为白色:

    export class MyNodeController extends NodeController {
      private rootNode: FrameNode | null = null;
      rootRenderNode: RenderNode | null = null;
      width: number = 0;
      height: number = 0;
    
      makeNode(uiContext: UIContext): FrameNode {
        this.rootNode = new FrameNode(uiContext);
        if (this.rootNode !== null) {
          this.rootRenderNode = this.rootNode.getRenderNode();
        }
        return this.rootNode;
      }
    
      aboutToResize(size: Size): void {
        this.width = size.width;
        this.height = size.height;
        if (this.rootRenderNode !== null) {
          this.rootRenderNode.backgroundColor = 0xFFFFFFFF;
          this.rootRenderNode.frame = { x: 0, y: 0, width: this.width, height: this.height };
        }
      }
    }
    
  2. 在NodeContainer的onTouch事件中创建并管理MyRenderNode实例,根据触摸事件更新绘制路径:

    onTouchEvent(event: TouchEvent): void {
      const positionX: number = vp2px(event.touches[0].x);
      const positionY: number = vp2px(event.touches[0].y);
      switch (event.type) {
        case TouchType.Down: {
          const newNode = new MyRenderNode();
          newNode.frame = { x: 0, y: 0, width: this.myNodeController.width, height: this.myNodeController.height };
          this.currentNode = newNode;
          this.currentNode.path.moveTo(positionX, positionY);
          if (this.myNodeController.rootRenderNode !== null) {
            this.myNodeController.rootRenderNode.appendChild(this.currentNode);
            this.nodeCount++;
          }
          break;
        }
        case TouchType.Move: {
          if (this.currentNode !== null) {
            this.currentNode.path.lineTo(positionX, positionY);
            this.currentNode.invalidate();
          }
          break;
        }
        case TouchType.Up: {
          this.currentNode = null;
          break;
        }
      }
    }
    
分享
微博
QQ
微信
回复
1天前
相关问题
鸿蒙如何实现位图绘制
9854浏览 • 1回复 待解决