Using the gpu module from the Blender Python API, we can draw images in the scene or viewport space. Images can be drawn in the scene coordinate system for intuitive mesh interaction, or in the viewport coordinate system to create custom UI elements.
Make the simplest example of drawing an image on the screen with the Blender Python API gpu module.
First, let’s draw the image in the scene space coordinate system.
Define a texture for drawing the image:
1 2 3 |
import gpu texture = gpu.texture.from_image(bpy.data.images['suzanne.png']) |
Create a shader to draw this texture:
1 |
shader = gpu.shader.from_builtin('2D_IMAGE') |
and a batch for rendering the shader:
1 2 3 4 5 6 7 8 9 10 |
from gpu_extras.batch import batch_for_shader batch = batch_for_shader( shader, 'TRI_FAN', { 'pos': ((0, 0), (2, 0), (2, 2), (0, 2)), 'texCoord': ((0, 0), (1, 0), (1, 1), (0, 1)), }, ) |
Pay attention on which coordinates are specified in the “pos” parameter. In this case, we want to display the image in scene space, so we specify the coordinates like we’re adding a simple plane to the scene and placing its corners at points (0,0), (2,0), (2,2), (0,2) in the XY scene plane.
Define a function for rendering the shader.
1 2 3 4 |
def draw(): shader.bind() shader.uniform_sampler('image', texture) batch.draw(shader) |
And add it to the draw handler to display the shader in the 3D viewport area:
1 |
bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_VIEW') |
Pay attention to the value of the fourth parameter – “POST_VIEW”. It determines that the image is displayed in the scene coordinate space.
When we need to display an image in the viewport coordinate space, we have to change the value of this parameter to the “POST_PIXEL”.
1 |
bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_PIXEL') |
We also need to change the coordinate values in the “pos” parameter when defining the batch to values in the viewport coordinate system:
1 2 3 4 5 6 7 |
batch = batch_for_shader( shader, 'TRI_FAN', { 'pos': ((100, 100), (200, 100), (200, 200), (100, 200)), 'texCoord': ((0, 0), (1, 0), (1, 1), (0, 1)), }, ) |
Here we specify the coordinates in pixels, from the lower left corner of the 3D Viewport area.
The rest of the code remains the same.
can we use gifs or other image formats?
You can use formats that Blender (openGL) can read.
how can i remove that image visualized?
Just remove draw() function from handler with
bpy.types.SpaceView3D.draw_handler_remove(draw, ‘WINDOW’)