Campbell Barton c3e5a35ecd PyAPI: add blf.bind_imbuf(..) context manager
Add support for using BLF to draw into an ImBuf image buffer.
Once the imbuf context has been set, draw calls for that font_id will draw into the image.

This works by binding an imbuf to BLF which is then used as the target when drawing.
```
with blf.bind_imbuf(font_id, imbuf):
    blf.draw_buffer(font_id, text)
```
See the example in the Python API documentation for reference.

The following BLF API's have been added to support a Python context manager.

- `BLF_buffer_state_push`.
- `BLF_buffer_state_pop`
- `BLF_buffer_state_free`

Ref !135772
2025-03-15 11:00:51 +11:00

30 lines
688 B
Python

"""
Drawing Text to an Image
++++++++++++++++++++++++
Example showing how text can be draw into an image.
This can be done by binding an image buffer (:mod:`imbuf`) to the font's ID.
"""
import blf
import imbuf
image_size = 512, 512
font_size = 20
ibuf = imbuf.new(image_size)
font_id = blf.load("/path/to/font.ttf")
blf.color(font_id, 1.0, 1.0, 1.0, 1.0)
blf.size(font_id, font_size)
blf.position(font_id, 0, image_size[0] - font_size, 0)
blf.enable(font_id, blf.WORD_WRAP)
blf.word_wrap(font_id, image_size[0])
with blf.bind_imbuf(font_id, ibuf, display_name="sRGB"):
blf.draw_buffer(font_id, "Lots of wrapped text. " * 50)
imbuf.write(ibuf, filepath="/path/to/image.png")