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.
Related Attributes
In this scenario, the following text style attributes are involved. For details, see TextStyle.
-
color: font color. The default value is white. Note that the font color must be different from the canvas color to ensure that the text can be properly displayed.
-
fontSize: font size, in units of px. The value is a floating point number. The default value is 14.0.
How to Develop
-
Obtain the canvas object through context.
let canvas = context.canvas; -
Initialize the text style. Set the font color to red and font size to 50.
// Obtain the text style. let myTextStyle: text.TextStyle = { // Text color. color: { alpha: 255, red: 255, green: 0, blue: 0 }, // Text size. fontSize: 100 }; -
Initialize the paragraph style.
let myParagraphStyle: text.ParagraphStyle = { textStyle: myTextStyle, }; -
Initialize the paragraph object and add text.
let fontCollection = text.FontCollection.getGlobalInstance(); let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection); // Push the text style. ParagraphGraphBuilder.pushStyle(myTextStyle); // Add text. ParagraphGraphBuilder.addText("Hello World"); -
Layout the paragraph and draw the text.
// Generate a paragraph. let paragraph = ParagraphGraphBuilder.build(); // Layout. paragraph.layoutSync(1250); // Draw the text. paragraph.paint(canvas, 0, 100);