目录

Drawing and Displaying Simple Text (ArkTS)

Overview

In a simple user interface, only a few lines of static text need to be displayed, such as the text on a label, button, menu item, or status bar. In this case, you only need to select a proper font, size, and color to complete the rendering.

How to Develop

  1. Obtain the canvas object through context.

    let canvas = context.canvas;
  2. Initialize the text style. Here, set the font color to red and the font size to 100 px.

    // Initialize the text style.
    let myTextStyle: text.TextStyle = {
      // Text color.
      color: {
        alpha: 255,
        red: 255,
        green: 0,
        blue: 0
      },
      // Text size.
      fontSize: 100
    };
  3. Initialize the paragraph style.

    let myParagraphStyle: text.ParagraphStyle = {
      textStyle: myTextStyle,
    };
  4. Initialize the paragraph object and add text.

    let fontCollection = text.FontCollection.getGlobalInstance();
    let paragraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
    // Push the text style.
    paragraphBuilder.pushStyle(myTextStyle);
    // Add text.
    paragraphBuilder.addText("Hello World");
  5. Layout the paragraph and draw the text.

    // Generate a paragraph.
    let paragraph = paragraphBuilder.build();
    // Layout.
    paragraph.layoutSync(1250);
    // Draw the text.
    paragraph.paint(canvas, 0, 100);

Effect