2
$\begingroup$

Is it possible to "write" in the viewport as statistic does?

enter image description here

or this?

enter image description here

...and no, i don't wanna parent text objects to my camera.... ;)

$\endgroup$
2

1 Answer 1

2
$\begingroup$

You can define a draw callback to do that and use blf module to draw the text you want.

Like for all callbacks, be sure to remove it when needed (add/remove should go in pairs so that you don't accumulate the drawings).

Here is a usage example with a modal operator (but you can also set it from a panel or others):

import bpy
# Blf is the blender module to draw fonts in the viewport
import blf

# A function to draw something (here mouse position)
def draw_callback_px(self, context):
    font_id = 0
    blf.position(font_id, 15, 100, 0)
    blf.size(font_id, 12, 72)
    blf.color(font_id, 1, 1, 1, 1)
    blf.draw(font_id, "Mouse position: " + str(self.mouse_pos) )

class ModalDrawOperator(bpy.types.Operator):
    """Draw a line with the mouse"""
    bl_idname = "view3d.modal_operator"
    bl_label = "Simple Modal View3D Operator"

    def modal(self, context, event):
        context.area.tag_redraw()

        if event.type == 'MOUSEMOVE':

            #Get the mouse position thanks to the event 
            #So that it is update for the next time draw callback will be fired
            self.mouse_pos = event.mouse_region_x, event.mouse_region_y

        elif event.type in {'ESC'}:
            # When finished remove the callback from the callback list
            bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
            return {'CANCELLED'}

        return {'PASS_THROUGH'}

    def invoke(self, context, event):
        if context.area.type == 'VIEW_3D':
            args = (self, context)
            
            # Install the draw callback named 'draw_callback_px'
            self._handle = bpy.types.SpaceView3D.draw_handler_add(draw_callback_px, args, 'WINDOW', 'POST_PIXEL')

            self.mouse_pos = [0,0]

            context.window_manager.modal_handler_add(self)
            return {'RUNNING_MODAL'}
        else:
            self.report({'WARNING'}, "View3D not found, cannot run operator")
            return {'CANCELLED'}


def register():
    bpy.utils.register_class(ModalDrawOperator)


def unregister():
    bpy.utils.unregister_class(ModalDrawOperator)

if __name__ == "__main__":
    register()
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .