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.
1 2 3 |
import blf font_id = blf.load('d:/Righteous-Regular.ttf') |
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.
1 |
font_id = 0 |
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:
1 2 3 4 5 |
def draw(font_id): blf.position(font_id, 100, 100, 0) blf.size(font_id, 100) blf.color(font_id, 0, 1, 1, 1) blf.draw(font_id, "Hello World") |
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.
1 2 3 |
bpy.types.SpaceView3D.draw_handler_add( draw, (font_id,), 'WINDOW', 'POST_PIXEL' ) |
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.
1 2 |
for area in bpy.context.screen.areas: area.tag_redraw() |
The full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import bpy import blf font_id = blf.load('d:/Righteous-Regular.ttf') def draw(font_id): blf.position(font_id, 100, 100, 0) blf.size(font_id, 100) blf.color(font_id, 0, 1, 1, 1) blf.draw(font_id, 'Hello World') bpy.types.SpaceView3D.draw_handler_add( draw, (font_id,), 'WINDOW', 'POST_PIXEL' ) for area in bpy.context.screen.areas: area.tag_redraw() |