Printing text on the 3D viewport area

Using the gpu module from the Blender Python API, we can draw not only images on the 3D viewport area, but also print arbitrary text. Printing text is carried out using the blf module – a wrapper over OpenGL.

To start, let’s load the font with which we will print the text from a file.

The load() function of the blf module returns a number – the identifier of the loaded font.

If it is not necessary to use external fonts, the font_id value can be set to 0, then the current Blender system font will be used.

The font identifier is passed as the first parameter to all blf functions responsible for displaying text on the screen.

Define a function that will display text on the 3D viewport area:

In the font_id parameter, we pass the previously defined font identifier to this function.

With the position() function, we set the position of the displayed text on the viewport area. The X, Y and Z coordinates are passed in the parameters. Position is counting from the lower left corner of the 3D viewport area.

The size() function sets the font size.

The font color is set using the color() function. Parameters are in the RGBA format, with values from 0.0 to 1.0.

And finally, the blf.draw() function draws the text passed in its parameter.

In order for our function to work, we need to connect it to the 3D viewport drawing handler.

In the first parameter, we pass a pointer to our function.

The second parameter is the list of arguments for our function. We pass the font_id. If necessary, we can pass more parameters by specifying them separated by commas.

The third parameter is the window region pointer.

And the fourth – the typo of the output to the screen. The “POST_PIXEL” value sets drawing in the screen coordinates.

Force redraw the areas so that the output text is immediately displayed on the viewport.

The full code:

5 2 votes
Article Rating
Subscribe
Notify of
guest

0 Comment
Inline Feedbacks
View all comments