目录

Integrating Instant Shape

After Instant Shape is integrated, the point information of strokes can be passed. When a stroke ends, you can hold your stylus/finger on the screen for a certain period of time to turn it into a regular shape.

Use Case

Implement Instant Shape in the app. The effect is as follows.

  1. Recognized image information can be obtained and stored.

  2. Information can be read from a stored image.

API Description

Class API Description
InstantShapeGenerator processTouchEvent(event: TouchEvent): void Processes a touch event.
InstantShapeGenerator getPathFromString(shapeString: string, penSize: number): Path2D Extracts shape information from a given shape string.
InstantShapeGenerator notifyAreaChange(width: number, height: number): void Notifies of component size changes.
InstantShapeGenerator setPauseTime(time: number): void Sets the pause time for triggering recognition, in ms.
InstantShapeGenerator release(): void Destroys the recognition tool.
InstantShapeGenerator onShapeRecognized(callback: Callback<ShapeInfo>): InstantShapeGenerator Registers a callback that is invoked when recognition is complete. This API returns the result asynchronously through a callback.

Development Procedure

  1. Import required modules. Construct the Instant Shape capability. The following uses a control as an example:

    import { InstantShapeGenerator, ShapeInfo} from '@kit.Penkit';
    
    @Entry
    @Component
    struct InstantShapeDemo {
      private instantShapeGenerator: InstantShapeGenerator = new InstantShapeGenerator();
      private points: DrawPathPointModel[] = [];
      // Draw a path.
      private drawPath = new Path2D();
      private shapePath = new Path2D();
      private mShapeSuccess = false;
      private settings: RenderingContextSettings = new RenderingContextSettings(true);
      private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
      // Obtain the recognition result using the callback method.
      private shapeInfoCallback = (shapeInfo: ShapeInfo) => {
        this.shapePath = shapeInfo.shapePath;
        this.mShapeSuccess = true;
        this.context.beginPath();
        this.context.reset();
        this.drawCurrentPathModel(this.shapePath);
      }
    
      aboutToAppear() {
        console.info('InstantShapeGenerator aboutToAppear');
        // Set the pause time for triggering recognition.
        try {
          this.instantShapeGenerator?.setPauseTime(280);
        } catch (error) {
          console.error(`Failed to setPauseTime. Code: ${error.code}, message: ${error.message}`);
        }
        // Register a callback that is invoked when recognition is complete.
        this.instantShapeGenerator?.onShapeRecognized(this.shapeInfoCallback);
      }
    
      aboutToDisappear() {
        console.info('InstantShapeGenerator aboutToDisappear');
        this.instantShapeGenerator?.release();
      }
    
      build() {
        Stack({ alignContent: Alignment.TopEnd }) {
          Canvas(this.context)
            .width('100%')
            .height('100%')
            .onAreaChange((oldValue: Area, newValue: Area) => {
              // Notify of component size changes. The shape size (for example, the radius of a circle) changes according to the dimensions of the component.
              this.instantShapeGenerator?.notifyAreaChange(Number(newValue.width), Number(newValue.height));
            }).onTouch((event: TouchEvent) => {
            // Process a touch event.
            this.instantShapeGenerator?.processTouchEvent(event);
            switch (event.type) {
              case TouchType.Down:
                this.moveStart(event.touches[0]?.x, event.touches[0]?.y);
                break;
              case TouchType.Move:
                this.moveUpdate(event.touches[0]?.x, event.touches[0]?.y);
                break;
              case TouchType.Up:
                this.moveEnd();
                break;
            }
          })
        }.height('100%').width('100%')
      }
    
      moveStart(x: number, y: number) {
        this.points.push({ x: x, y: y });
        this.drawPath.moveTo(x, y);
        this.drawCurrentPathModel(this.drawPath);
        this.mShapeSuccess = false;
      }
    
      moveUpdate(x: number, y: number) {
        let lastPoint = this.points[this.points.length - 1];
        this.points.push({ x: x, y: y });
        this.drawPath.quadraticCurveTo((x + lastPoint?.x) / 2, (y + lastPoint?.y) / 2, x, y);
        if (!this.mShapeSuccess) {
          this.drawCurrentPathModel(this.drawPath);
        }
      }
    
      moveEnd() {
        this.points = [];
        this.drawPath = new Path2D();
        this.shapePath = new Path2D();
      }
    
      private drawCurrentPathModel(path: Path2D) {
        this.context.globalCompositeOperation = 'source-over';
        this.context.lineWidth = 8;
        this.context.strokeStyle = '#ED1B1B';
        this.context.lineJoin = 'round';
        this.context.stroke(path);
      }
    }
    
    export class DrawPathPointModel {
      public x: number = 0;
      public y: number = 0;
    }